由于当时项目是多个公司合作,有些接口是跨域调用别人写的,后端无法监听。所以在后端做登录超时处理很麻烦,最后就由前端来写。
这里是通过cookie的过期时间去实现超时处理的。用的环境是vue,在axios拦截器中实现
main.js
//isRefuse 判断是否已经拦截了,否则可能出现同时调用多个接口出现几个弹框
var isRefuse = false;
// axios请求拦截器
axios.interceptors.request.use(function (config) {
//arr存储不需要登录就可以使用的页面名称
//cookie是在登录成功后存储的,如果不需要登录的界面访问接口就应该不拦截,如果都需要拦截可以忽略
if(arr.indexOf(router.history.current.name)!=-1){
return config; // 在发送请求之前做些什么
}
if(document.cookie){ //cookie存在且未过期
auth.reSetCookie(); //重置cookie过期时间,具体方法在下方auth.js
return config;
}else if(!isRefuse){//如果还未拦截
isRefuse = true;
Vue.prototype.$alert('登录已过期请重新登陆', '提示', {
confirmButtonText: '确定',
callback: action => {
//清理session
sessionStorage.clear();
isRefuse = false;
//返回登录
router.push({
path:'/login'
})
}
});
return Promise.reject('登录过期');
// Vue.prototype.$message.error('登录已过期请重新登陆');
}
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
/*******************/
//如果后端处理
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
if(response.data.code==403){
// 过期退出登录
}
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
console.log(error)
return Promise.reject(error);
});
auth.js
export default{
//加密方法,根据需求选择合适的依赖去处理
Encrypt(){}
//解密方法
Decrypt(){}
// cookie存取
setCookie(form){
//设置名称为name,值为value的Cookie
let expdate = new Date(); //初始化时间
//时间单位毫秒,设置 Cookie 的过期时间,1000表示1s这里是30分钟过期
expdate.setTime(expdate.getTime() + 30 * 60 * 1000);
for(let i in form){
let a = form[i];
if(i=='password'){
a = this.Encrypt(form[i]) //如果有密码加密,在前端登录做保存密码操作
}
document.cookie = i+'='+a+";expires="+expdate.toGMTString()+";path=/";
// Expires 用于设置 Cookie 的过期时间。 Expires 的值为 Session,表示的就是会话性 Cookie
//即document.cookie= name+"="+value+";path=/"; ,因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!
}
},
//重置cookie过期时间
reSetCookie(){
let cookie = document.cookie;
let expdate = new Date();
expdate.setTime(expdate.getTime() + 30 * 60 * 1000);
document.cookie = cookie+";expires="+expdate.toGMTString()+";path=/";
},
//获取cookie,将cookie字符串转化为对象
getCookie(){
let form = {}
if (document.cookie.length>0)
{
let arr = document.cookie.split('; ');
arr.forEach(a=>{
let ar = a.split('=')
let name = ar[0];
let value = ar[1];
if(name=='password'){
value = this.Decrypt(value) //解密
}
form[name] = value
})
}
return form
},
}
···