vue-resource get/post請求如何攜帶cookie的問題

vue-resource get/post請求如何攜帶cookie的問題html

當咱們使用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不會;vue

爲了方便,咱們這邊是封裝了一個get請求,只要在get請求添加參數 { credentials: true } 便可使用;web

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請求中,咱們須要添加以下代碼:ajax

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

Vue.http.interceptors 是攔截器,做用是能夠在請求前和發送請求後作一些處理,加上上面的代碼post請求就能夠解決攜帶cookie的問題了;
所以咱們的post請求也封裝了一下,在代碼中會添加如上解決post請求攜帶cookie的問題了;以下代碼:json

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); } }) };
相關文章
相關標籤/搜索