跨域问题花式踩坑(一)

2020-05-15  本文已影响0人  黑面书生94614

踩坑惨状

平时微信分享配置文件都是后台配置好放到服务器上,前端直接引用,后续因业务需要,更改为可自定义分享内容,通过前端接收后台配置,来实现自定义分享,此时单纯的我还不知道,一个大坑正在前方等待着我的到来……

Access to XMLHttpRequest at 'http://map.museum.chaoxing.com/beacon/config?urlhttp://file.museum.chaoxing.com/frontendTest/standard/index.html#/' from origin 'http://file.museum.chaoxing.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
image

踩坑分析:

一脸懵逼的我谷歌百度齐上阵,博客文档翻起来,终于功夫不负有心人,让我在阮一峰老师的博客里找到了答案,这篇博文深入浅出、全面透彻的讲解了跨域问题,安利一波~

跨域资源共享 CORS 详解

如果要发送Cookie,Access-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名。同时,Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传,且(跨源)原网页代码中的document.cookie也无法读取服务器域名下的Cookie。

这是就是因为前端在拦截http请求时,设置了withCredentials: true

const http = axios.create({
  baseURL: window.SITE_CONFIG.baseUrl, // api 的 base_url
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
})

脱坑指南

CORS请求默认不发送Cookie和HTTP认证信息。如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow-Credentials字段。
Access-Control-Allow-Credentials: true

另一方面,开发者必须在AJAX请求中打开withCredentials属性。
var xhr = new XMLHttpRequest(); xhr.withCredentials = true;
否则,即使服务器同意发送Cookie,浏览器也不会发送。或者,服务器要求设置Cookie,浏览器也不会处理。

但是,如果省略withCredentials设置,有的浏览器还是会一起发送Cookie。这时,可以显式关闭withCredentials。

所以如果不需要将Cookie发送到服务器,只需要设置withCredentials: false就可以啦,如果有发送Cookie的需求,那便需要联系后端小伙伴将Access-Control-Allow-Origin的*号更改为明确的、与请求网页一致的域名就可以啦~

新知识get! 觅食去也~

上一篇下一篇

猜你喜欢

热点阅读