Axios + CORS cross domain requests carry cookies

Time:2020-7-20

Axios + CORS cross domain requests carry cookies

Solution: CORS

front end

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

Back end configuration response header

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

After setting, cross domain request carrying can be realizedCookieYes.

Abnormal situation

After setting the above steps, set theRequest HeadersStill not carrying itCookie
interceptXMLHttpRequest

(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);

it turns out to be the case thatMockJsRevisedXMLHttpRequest

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

Manual settingwithCredentials

Mock.XHR.prototype.withCredentials = true;

Problem solving.