需求:在请求头中添加token,网上借鉴了几份代码,没有成功,以下是实践出来的,记录下代码
Vue.http.interceptors.push(function (request, next) {
// modify url 本地调试使用本地ip地址
const url = '';
request.url = `${url}${request.url}`;
// modify headers
if (store.getters.getToken) {
request.headers.set('token', `${store.getters.getToken}`);
}
// request.headers.set('X-CSRF-TOKEN', 'TOKEN');
next((response) => {
// 请求发送后的处理逻辑
if (response.status === 400 || response.status === 401) {
// 当 Token 已经失效时,清空所有保存在 setToken 的数据
}
return response;
});
});
注意:在添加token是,是需要后台进行允许的,Access-Control-Allow-Headers:token
Access-Control-Allow-Headers:Accept,Pragma,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token
Access-Control-Allow-Methods:GET, POST, DELETE, PUT,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Allow:GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH
Date:Thu, 15 Jun 2017 13:19:16 GMT
Transfer-Encoding:chunked
如果没有允许则会报一下错误,你没有权限
Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
参考地址
https://github.com/pagekit/vue-resource/blob/master/docs/http.md#options