Axios + CORS 跨域請求攜帶Cookie

Axios + CORS 跨域請求攜帶Cookie

解決方法:CORS

前端javascript

axios.interceptors.request.use(config => {
  config.withCredentials = true;
  return config;
});

後端配置響應頭前端

"Access-Control-Allow-Origin": Request Headers Origin
"Access-Control-Allow-Credentials": true

設置完以後,就能夠實現跨域請求攜帶 Cookie 了。java

異常狀況

按上面的步驟設置完以後,在 Request Headers 依然沒有攜帶 Cookie
攔截 XMLHttpRequestios

(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 修改了 XMLHttpRequestaxios

// mock.js
if (XHR) window.XMLHttpRequest = XHR

手動設置 withCredentials後端

Mock.XHR.prototype.withCredentials = true;

問題解決。跨域

相關文章
相關標籤/搜索