当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 前端处理登录超时

前端处理登录超时

2020年07月17日  | 移动技术网IT编程  | 我要评论

由于当时项目是多个公司合作,有些借口是跨域调用吧别人写的,后端无法监听。所以在后端做登录超时处理很麻烦,最后就由前端来写。
这里是通过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
    }else if(!isRefuse){//如果还未拦截
        isRefuse = true;
        Vue.prototype.$alert('登录已过期请重新登陆', '提示', {
            confirmButtonText: '确定',
            callback: action => {
            	//清理session和cookie
                sessionStorage.clear();	
                auth.setCookie({});
                isRefuse = false;
                //返回登录
                router.push({
                    path:'/login'
                })
            }
        });
        // Vue.prototype.$message.error('登录已过期请重新登陆');
    }
    // 在发送请求之前做些什么
    return config;
}, 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

// cookie存取
setCookie(form){
    //设置名称为name,值为value的Cookie
    let expdate = new Date();   //初始化时间
     //时间单位毫秒,设置 Cookie 的过期时间,1000表示1s这里是30分钟过期
    expdate.setTime(expdate.getTime() + 30 * 60 * 1000);  
    let msg = []
    for(let i in form){
        let a = form[i];
        if(i=='password'){
            a = this.Encrypt(form[i])	//如果有密码加密
        }
        msg.push(i+'='+a);
    }
    // Expires 用于设置 Cookie 的过期时间。 Expires 的值为 Session,表示的就是会话性 Cookie
    document.cookie = msg.join(':')+";expires="+expdate.toGMTString()+";path=/";
    //即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  
},
···

本文地址:https://blog.csdn.net/qq_41488724/article/details/107380270

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网