The problem of how vue-resource get/post requests carry cookies

The problem of how vue-resource get/post requests carry cookies

When we use vue request, we will find that the request header does not carry cookies to the background, we can add the following code to the request:
vue.http.options.xhr = { withCredentials: true}; The function is to allow cross-domain The request carries a cookie for authentication;
vue.http.options.emulateJSON = true; the function is that if the web server cannot handle the application/json request, we can enable the emulateJSON option;
after enabling this option, the request will be application/x-www -form-urlencoded as MIME type, same as normal html form. Add the following code, the code returned by the get request will
carry the cookie, but the post will not;

For convenience, we encapsulate a get request here, as long as the parameter { credentials: true } is added to the get request, it can be used;

const ajaxGet = (url, fn) => {
  let results = null;
  Vue.http.get(url, { credentials: true }).then((response) => {
    if (response.ok) {
      results = response.body;
      fn(1, results);
    } else {
      fn(0, results);
    }
  }, (error) => {
    if (error) {
      fn(0, results);
    }
  });
};

The above will only carry the cookie for the get request, but the post request still has no effect, so in the post request, we need to add the following code:

Vue.http.interceptors.push((request, next) => {
  request.credentials = true;
  next();
});

Vue.http.interceptors is an interceptor. Its function is to do some processing before the request and after sending the request. Adding the above code post request can solve the problem of carrying cookies;
therefore, our post request is also encapsulated, in The code will add the above to solve the problem of post request carrying cookies; the following code:

const ajaxPost = (url, params, options, fn) => {
  let results = null;

  if (typeof options === 'function' && arguments.length <= 3) {
    fn = options;
    options = {};
  }
  Vue.http.interceptors.push((request, next) => {
    request.credentials = true;
    next();
  });
  Vue.http.post(url, params, options).then((response) => {
    if (response.ok) {
      results = response.body;
      fn(1, results);
    } else {
      fn(0, results);
    }
  }, (error) => {
    if (error) {
      fn(0, results);
    }
  })
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324770814&siteId=291194637