目 录
1. 在登录页面,调用登录的接口后,直接获取当前时间并保存在本地,类似保存token。
2. 在路由守卫 获取本机存储的时间戳,加15分钟与当前时间进行对比,如果大于当前时间说明token失效,直接跳转到登录页。
1. 直接在导航守卫儿判断 token是否 还存在,不存在就跳转至登录页。
前端设置:
方法一:
1. 在登录页面,调用登录的接口后,直接获取当前时间并保存在本地,类似保存token。
代码:
// 点击登录 login(form) { this.$refs[form].validate((valid) => { if (valid) { this.$API.Login(this.form).then((res) => { // console.log(res, "11111111111"); if (res.data.code === 200) { this.$message({ message: "登录成功啦", type: "success", showClose: true, }); // 将登录名使用vuex传递到Home页面 this.$store.commit("handleUserInfo", res.data.data); // 加入 token localStorage.setItem("token", res.data.data.token); // 添加时间戳 //待写 // 跳转到首页 // console.log(1111111); this.$router.replace("/index"); } }); } else { //lu 新加 this.$message({ message: "登录失败,请重新登录", type: "error", showClose: true, }); return false; } }); },
2. 在路由守卫 获取本机存储的时间戳,加15分钟与当前时间进行对比,如果大于当前时间说明token失效,直接跳转到登录页。
ps:
1. 加15分钟,是因为我这个项目后端设的是20分钟token失效。这个时间可以根据项目随机设置。
2. 大部分项目中token过期是由后端提供,前端只需在拦截那儿判断即可。
方法二:
1. 直接在导航守卫儿判断 token是否 还存在,不存在就跳转至登录页。
// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {
if (to.path === "/login") {
next();
} else {
let token = localStorage.getItem("Token");
if (token === null || token === "" || token === undefined) {
console.log(token, "进行判断的token");
next("/login");
} else {
document.title = "项目标题";
next();
}
}
});