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