token过期后记录当前页面路由,重新登陆跳转至原页面

实现当token过期,重新登录后返回原页面

思路:在响应拦截器中获取到token过期的状态码401,使用router.currentRoute.fullPath方法获取到当前页面的路由地址,以路径参数的形式放到登录页面地址的后面。重新登陆后,使用this.$route.query方法获取路径地址参数并跳转至该路由页面。

代码:

//响应拦截其中

//导入router
	import router from '../router'


    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true
        MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            isRelogin.show = false
            store.dispatch('LogOut').then(() => {
              // router.currentRoute.fullPath,获取跳转前的地址,放到登录页面地址的后面
              // 防止地址含有特殊字符,使用encodeURIComponent()方法将其转义
              router.push({ path: `/login?path=${encodeURIComponent(router.currentRoute.fullPath)}` })
            })
          })
          .catch(() => {
            isRelogin.show = false
          })
      }
      return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
    }
//登录函数
handleLogin() {
		this.$store.dispatch("Login", this.loginForm)
            .then(() => {
              // 使用decodeURIComponent()进行解码
              this.$router
                .push({
                  decodeURIComponent(this.$route.query.path) !== "undefined" ? decodeURIComponent(this.$route.query.path) : "/",
                })
                .catch(() => {});
         })
	}

注意:当原页面路径地址含有多个路径参数时(含有&等特殊符号),需要使用encodeURIComponent()方法将其转义。在登录时使用decodeURIComponent()函数进行解码。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值