利用路由守卫实现token过期后返回登录界面

发布时间 2023-11-06 21:33:38作者: 天启A
const timeX = localStorage.getItem("time");
//如果有时间戳存在会判断token是否过期
if(timeX!==null){
const time=timeX.slice(1,-1)//获取了token的过期时间
const tokenTime=new Date(time);

const currentTimeUS=new Date();
const currentTimeCN=new Date(currentTimeUS.getTime()+8*60*60*1000)

if(currentTimeCN>tokenTime&& to.path !== '/login' && to.path !== '/register'){
localStorage.removeItem("user")
localStorage.removeItem("time")
return next('/login')
}
//在登录的时候往localstorage中塞一个date
const currentDate=new Date();
const tokenUselessDate=new Date(currentDate.getTime()+10*60*60*1000);
localStorage.setItem("time",JSON.stringify(tokenUselessDate));

最后加上登录状态异常的弹窗,完善了退出登录时的提醒

 总结:这次遇到了不少坑,完成这一个小操作居然花了我2个小时

1.从localstorage中取出来的"time"是带引号的,如果直接丢给date格式化处理他会返回不了正确时间

2.vue的报错一定要仔细看浏览器的控制台,一开始我写入的时候timeX可能为空,后面还有对他进行字符串格式化的处理会导致一旦这玩意取不出来,整个页面就不显示了。

3.一定要注意不要在路由中形成环,我在路由中把登录注册内不包含信息给写上了,不然也会整个页面不显示