vue get/post请求如何携带cookie的问题

一:

只需要在main.js中写这三行代码即可

import axios from 'axios'

axios.defaults.withCredentials=true;//让ajax携带cookie

Vue.prototype.$axios = axios;

如果cookie携带不过去的话,请求响应的时候他会报错显示登陆过期的呦!!!

顺便说一下原生js携带cookie的方法:

            xhrFields: {
               withCredentials: true
            },

加一段上述代码即可
来源:https://blog.csdn.net/liuxin_1991/article/details/81531321

当我们使用vue请求的时候,我们会发现请求头中没有携带cookie传给后台,我们可以在请求时添加如下代码:
vue.http.options.xhr = { withCredentials: true}; 的作用就是允许跨域请求携带cookie做身份认证的;
vue.http.options.emulateJSON = true; 的作用是如果web服务器无法处理 application/json的请求,我们可以启用 emulateJSON 选项;
启用该选项后请求会以 application/x-www-form-urlencoded 作为MIME type, 和普通的html表单一样。 加上如下代码,get请求返回的代码会
携带cookie,但是post不会;

为了方便,我们这边是封装了一个get请求,只要在get请求添加参数 { credentials: true } 即可使用;

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

如上只会对get请求携带cookie,但是post请求还是没有效果的,因此在post请求中,我们需要添加如下代码:

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

Vue.http.interceptors 是拦截器,作用是可以在请求前和发送请求后做一些处理,加上上面的代码post请求就可以解决携带cookie的问题了;
因此我们的post请求也封装了一下,在代码中会添加如上解决post请求携带cookie的问题了;如下代码:

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

来源:https://www.cnblogs.com/tugenhua0707/p/8923177.html

猜你喜欢

转载自www.cnblogs.com/huchong-bk/p/12122934.html
今日推荐