vue中前端处理token过期的方法与axios请求拦截处理

时间:2023-03-09 01:16:05
vue中前端处理token过期的方法与axios请求拦截处理

在处理token过期的这个问题上困扰了我很久,现在终于解决的了,所以分享出来给大家,希望能够对大家有所帮助。

首先,当然是路由进行拦截,路由拦截当然是在beforeEach中了:


router.beforeEach((to, from, next) => {

    iView.LoadingBar.start();
//Util.title(to.meta.title, router.app);
Util.title(to.meta.title); if (Cookies.get('locking') === '1' && to.name !== 'locking') { // 判断当前是否是锁定状态
next({
replace: true,
name: 'locking'
});
} else if (Cookies.get('locking') === '0' && to.name === 'locking') {
next(false);
} else { if (!Cookies.get('status') && to.name !== 'login') { // 判断是否已经登录且前往的页面不是登录页
//alert('登录过期!请重新登录!'); next({
name: 'login'
});
} else if (Cookies.get('status') && to.name === 'login') { // 判断是否已经登录且前往的是登录页
Util.title();
next({
name: 'home_index'
});
} else {
Util.toDefaultPage(routers, to.name, router, next);
next();
}
}
// }) // } });

路由拦截过后,当然就到了axios的拦截,在每次的后台请求中拦截一次判断后台token是否过期:

//请求时的拦截
util.ajax.interceptors.request.use(function(config){
const token = Cookies.get('status');
if (token) {
// config.headers.common['Authorization'] = token;
config.headers.Authorization = token;
}
return config
},function(error){ return Promise.reject(error);
}); //响应时的拦截
util.ajax.interceptors.response.use(response => {
//对响应数据做操作
if (response.data.msg == '登录失效') { //这里是判断后台的token是否过期 Cookies.remove("status"); //如果过期则清除前端的token并跳转到登录页
//这里需要说明一下,如果你是用的是hash模式,使用下面的就可以了 ,如果使用的是history 模式则使用window.location.href='/login';就可以了
window.location.href='#/login';
}
return response; },error => {
//对响应数据错误做操作
debugger
if(response.data.code == 1000000) { Cookies.remove("status");
window.location.href='#/login' return Promise.reject(response);
}
return Promise.reject(error);
});

axios的拦截我是写在util.js的文件中的;

下面是我的公众号,欢迎大家关注,可以一起学习一起进步:

vue中前端处理token过期的方法与axios请求拦截处理