Axios + CORS 跨域请求携带Cookie
解决方法:CORS
前端
axios.interceptors.request.use(config => {
config.withCredentials = true;
return config;
});
后端配置响应头
"Access-Control-Allow-Origin": Request Headers Origin
"Access-Control-Allow-Credentials": true
设置完之后,就可以实现跨域请求携带 Cookie
了。
异常情况
按上面的步骤设置完之后,在 Request Headers
依然没有携带 Cookie
。
拦截 XMLHttpRequest
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
this.addEventListener(
'readystatechange',
function() {
console.log(this); // MockXMLHttpRequest
},
false
);
open.call(this, method, url, async, user, pass);
};
})(XMLHttpRequest.prototype.open);
原来是 MockJs
修改了 XMLHttpRequest
// mock.js
if (XHR) window.XMLHttpRequest = XHR
手动设置 withCredentials
Mock.XHR.prototype.withCredentials = true;
问题解决。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。