Vue路由守卫无限重定向问题及token校验登录跳转解决方案
Vue路由守卫无限重定向问题修复及Token验证逻辑实现
问题分析
你遇到的无限重定向错误,根源在于当前路由守卫的逻辑漏洞:当没有Token时,无论当前要访问的是不是登录页,都会强制跳转到登录页。而登录页的requiresAuth设为false,每次进入登录页时,因为Token为空,又会触发跳转逻辑,形成循环。
错误提示:
Detected an infinite redirection in a navigation guard when going from "/" to "/". Aborting to avoid a Stack Overflow. This will break in production if not fixed
现有路由守卫代码:
router.beforeEach((to, from, next ) =>{ console.log(to.meta) let tokens = JSON.parse(localStorage.getItem('chikolo_tokens')) if (tokens!== null && to.meta.requiresAuth) { next() } else{ next({ name: 'login' }) } })
现有路由配置:
{ path: '/', name: 'login', component: Login, meta: { requiresAuth: false }, }, { path: '/admin/home/', name: 'home', component: AdminHome, meta: { requiresAuth: true }, }, { path: '/admin/users/', name: 'adminUsers', component: Users, meta: { requiresAuth: true }, },
正确实现逻辑
修复无限重定向,同时完善Token验证流程,代码如下:
router.beforeEach(async (to, from, next) => { // 1. 如果目标路由是登录页,直接放行,避免循环 if (to.name === 'login') { return next() } // 2. 处理需要权限的路由 if (to.meta.requiresAuth) { const tokens = JSON.parse(localStorage.getItem('chikolo_tokens')) // 2.1 没有Token,跳转到登录页 if (!tokens) { return next({ name: 'login' }) } try { // 2.2 调用API验证Token有效性 const response = await axios.post('/api/verify-token', { token: tokens.access }) if (response.data.valid) { // Token有效,放行 next() } else { // Token无效,清除本地存储并跳登录 localStorage.removeItem('chikolo_tokens') next({ name: 'login' }) } } catch (error) { // 请求失败(比如Token过期、网络问题),清除Token并跳登录 localStorage.removeItem('chikolo_tokens') next({ name: 'login' }) } } else { // 3. 不需要权限的路由(除登录页外的其他公开路由),直接放行 next() } })
关键逻辑说明
- 登录页特殊处理:优先判断目标路由是否为登录页,直接放行,从根源避免无限循环。
- Token存在性检查:对需要权限的路由,先判断本地是否有Token,没有则直接跳登录。
- Token有效性验证:通过API验证Token是否有效,验证失败或请求异常时,清除本地Token再跳转登录,避免无效Token残留。
- 异步处理:因为API请求是异步操作,需要用
async/await确保逻辑顺序正确。
内容的提问来源于stack exchange,提问作者Isaac Hatilima
相关产品推荐
相关产品推荐

