登录之后的请求会带登录用户信息,需要把登录时的cookie设置到之后的请求头里面。而跨域请求要想带上cookie,必须要请求属性withCredentials=true,这是浏览器的同源策略导致的问题:不允许JS访问跨域的Cookie。
withCredentials 属性是一个Boolean类型,它指示了是否该使用类似cookies,authorization,headers(头部授权)或者TLS客户端证书这一类资格证书来创建一个跨站点访问控制(cross-site Access-Control)请求。
- axios的Ajax请求
//vue的main.js
axios.defaults.withCredentials = true;//允许跨域携带cookie信息
- JQuery的Ajax请求
$.ajax({
type: "GET",
url: url,
xhrFields: {
withCredentials: true // 允许跨域携带cookie信息
},
processData: false,
success: function(data) {}
});
- XMLHttpRequest的Ajax请求
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true; // 允许跨域携带cookie信息
xhr.send();
但是前端这样设置之后发现报错了!
Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: 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.
原因是:前端设置withCredentials的情况下,后端要设置Access-Control-Allow-Origin为你的源地址,例如http://localhost:8080,而且还要设置header(‘Access-Control-Allow-Credentials: true’);
另外,Access-Control-Allow-Origin不能设置为*,不然cookie不会出现在http的请求头里,所以报错里说Access-Control-Allow-Origin不能是*。
上一篇: 前端发展简史
下一篇: 你想知道的关于Cookie的所有事