vue get / post requests on how to carry cookie problem

One:

Only three lines of code to write this in the main.js

import axios from 'axios'

axios.defaults.withCredentials = true; // make ajax carry cookie

Vue.prototype. $ Axios = axios;

If the cookie does not carry the words of the past, when he would respond to a request to display an error landing expired Yo! ! !

By the way native js carrying cookie method:

            xhrFields: {
               withCredentials: true
            },

With a piece of code above
Source: https://blog.csdn.net/liuxin_1991/article/details/81531321

 

When we use vue request, we will find that the request does not carry the first cookie to the backed, we can add the following code request:
vue.http.options.xhr = {withCredentials: to true};  role is allowed Cross request carries the authentication cookie do;
vue.http.options.emulateJSON = to true;  the role is if the web server can not handle application / json request, we can enable emulateJSON option;
this option enabled, the request will be  application / x-www -form-urlencoded  as a MIME type, and the same as ordinary html form. Add the following code, get a request code returned will
carry the cookie, but the post will not;

For convenience, we are here encapsulates a get request, as long as the get request to add parameters {credentials: true} 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);
    }
  });
};

As it will only get request carries cookie, but the post request or no effect, so the post request, we need to add the following code:

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

Vue.http.interceptors is interceptor role is to do some processing before and after the request and send the request, together with the above code post requests can solve the problem of carrying the cookie;
therefore our post request also encapsulates it in the code will be added to the above problem of a post request carries cookie; 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);
    }
  })
};

Source: https://www.cnblogs.com/tugenhua0707/p/8923177.html

Guess you like

Origin www.cnblogs.com/huchong-bk/p/12122934.html