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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM