You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js令牌过期后进入登录页时陷入循环问题求助

解决Vue.js中Token过期后登录页面循环问题

核心原因

路由全局守卫没正确排除登录页的校验逻辑,导致进入登录页后仍触发token过期校验,重复跳转到登录页,形成死循环。

具体解决方案

1. 全局路由守卫中排除登录页

在router.beforeEach里先判断当前路由是否是登录页,是就直接放行,不执行token校验:

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 登录页直接放行,不校验token
  if (to.path === '/login') {
    next()
    return
  }

  // 其他页面校验token有效性
  if (token) {
    try {
      // 这里用jwt解析token,需先安装jsonwebtoken包
      const decoded = jwt.decode(token)
      // 检查token是否过期(exp是秒级时间戳,转毫秒和当前时间对比)
      if (decoded.exp * 1000 < Date.now()) {
        localStorage.removeItem('token')
        next('/login')
      } else {
        next()
      }
    } catch (err) {
      // token解析失败,视为无效
      localStorage.removeItem('token')
      next('/login')
    }
  } else {
    // 无token直接跳登录
    next('/login')
  }
})

2. 清理登录页内的自动跳转逻辑

检查登录页的created/mounted钩子,别写无判断的自动跳转代码,只有token有效时才跳首页:

<script>
export default {
  created() {
    const token = localStorage.getItem('token')
    if (token) {
      try {
        const decoded = jwt.decode(token)
        // 仅当token未过期时才跳转首页
        if (decoded.exp * 1000 > Date.now()) {
          this.$router.push('/home')
        }
      } catch (err) {
        // token无效,留在登录页
      }
    }
    // 无token时正常显示登录表单
  }
}
</script>

3. 接口拦截器添加防重复跳转标记

如果是接口返回401触发跳转,加个标记避免多个并发请求重复跳登录:

import axios from 'axios'
import router from './router'

let isRedirecting = false // 标记是否正在跳转登录

axios.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401 && !isRedirecting) {
      isRedirecting = true
      localStorage.removeItem('token')
      // 跳转完成后重置标记
      router.push('/login').finally(() => {
        isRedirecting = false
      })
    }
    return Promise.reject(err)
  }
)

关键提醒

  • 所有校验token的逻辑必须排除登录页面,这是解决循环的核心。
  • 跳登录前一定要清除过期token,避免残留token干扰后续逻辑。
  • 接口拦截器的防重复标记能避免多请求同时触发跳转,防止多次执行登录页跳转。

内容的提问来源于stack exchange,提问作者Bohodir Boboyev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:33:30