我的路由器出现错误,并且不知道如何解决。
此全局路由器应检查jwt令牌到期并处理路由。在添加诸如isActivated
帐户之类的功能之前,一切工作正常。因此,现在我需要检查用户是否具有令牌以及用户帐户是否已激活。
1)如果用户拥有令牌,则应创建next(),否则创建next(“ / login”)(重定向)
2)如果用户具有令牌,但尚未激活其帐户(首次登录),则应在设置页面的next(“ / setup”)上重定向,直到他提交一些信息。
所以这是我的警卫
router.beforeEach((to, from, next) => {
const token = localStorage.getItem("token");
const tokenExp = parseInt(localStorage.getItem("tokenExp"))
const isActivated = localStorage.getItem("isActivated")
const now = new Date().getTime() + 129600000
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
console.log("first")
if (requiresAuth && !token) {
next('/login');
} else if (requiresAuth && token) {
if (now > tokenExp) {
axios.post("/user/t/r", token)
.then(e => {
const token = e.headers['authorization'].replace("Bearer ", "");
localStorage.setItem("token", token);
localStorage.setItem("tokenExp", (new Date().getTime() + 172800000).toString())
if (isActivated === 'true') {
next()
} else {
next("/setup")
}
})
.catch(e => {
localStorage.removeItem("token")
localStorage.removeItem("tokenExp")
localStorage.removeItem("fullName")
localStorage.removeItem("role")
next('/login')
})
} else {
console.log("second")
if (isActivated === 'true') {
console.log("third")
next();
} else {
console.log("fourth")
next("/setup")
}
}
} else {
next();
}
})
这是我登录时出现错误的console.log:
答案 0 :(得分:1)
您将无限重定向到/ setup,您的第一次运行代码会命中“第四”,然后将用户发送到/ setup,在该位置再次调用之前,您的无限循环就会开始。
如果用户已经在该页面上,则需要停止调用next('/ setup')或next('/ login')。
您需要使用router.currentRoute,以确保您不会重定向到它们已经打开的页面。