给每个axios请求都添加一个前置拦截器,发送请求时添加请求头,在第一次后台发给前台一个jsessionid后,前台永久保存在浏览器端,在第二次
...第n次进行操作发送请求时,都把
这个jsessionid传给后台,就可以获取到已登录用户,进行操作 (有些功能是必须登录才能操作的
. )
axios
.interceptors
.request
.use(config
=>{
let uToken
= localStorage
.getItem("token");
if(uToken
){
config
.headers
['U-TOKEN']=uToken
;
}
return config
;
},error
=> {
Promise
.reject(error
);
});
使用:在axios发送请求后,得到一个res对象,进行回调函数前的拦截器
axios
.interceptors
.response
.use(res
=>{
let {success
, result
} = res
.data
;
if(!success
&& result
==="noUser"){
location
.href
= "/login.html";
return;
}
if(!success
&& result
==="expireUser"){
localStorage
.removeItem("token");
localStorage
.removeItem("loginUser");
location
.href
= "/login.html";
return;
}
return res
;
},error
=> {
Promise
.reject(error
);
})