axios發送請求以前和請求回來以後

var $ajax = axios.create();
//向服務器發出請求時ios

1 $ajax.interceptors.request.use(config => {
2 if (localStorage.JWT_TOKEN) {//本地存在時 添加表頭x-access-token
3 config.headers = {'x-access-token': localStorage.JWT_TOKEN};
4 };
5 loading.className = 'loadingWrap active';
6 return config;
7 }, err => {
8 console.error(err);
9 });

 


//接收服務響應時 ajax

$ajax.interceptors.response.use(res => {
if(res.data.status === 400){//登陸超時
alert("登陸已超時,請從新登陸");
localStorage.removeItem("JWT_TOKEN");
window.location.href = "/views/login";
return false;
}else{
localStorage['JWT_TOKEN'] = res.headers["x-token-new"];//與後臺交互時 從新設置過期時間
loading.className = 'loadingWrap';    
return res.data;
}
}, err => {
console.error(new Error(res.data.msg));
});

Vue.prototype.$ajax = $ajax;
相關文章
相關標籤/搜索