var $ajax = axios.create();
//向服务器发出请求时
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.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;