关于用户没有权限路由守卫跳转登录后页面跳转,返回之前浏览页面处理方法

路由守卫需要登录跳转后重回页面

问题:当我们访问页面需要token,路由守卫就会使跳转到登录页面,
这时如我们没有进行重定向就会跳转到个首页或者人中心页面。
解决方法:在响应拦截器里面,没有token的状态码进行判断,捕获401状态码

设置响应拦截
跳转带hash参数
window.location.href = /#/login?redirectURL=${window.location.hash.substr(1)}

axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    if (response.data.statusCode == 401) {
        window.location.href = `/#/login?redirectURL=${window.location.hash.substr(1)} `   
        //当请求返回401,用户没有登录,直接送回首页 加上hash参数
    }
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

登录页面获取hash为 console.log(window.location.hash)

 console.log(window.location.hash)
  //得到 /#/login?redirectURL=%2Farticaldetail%2F12

关键我们需要

decodeURIComponent(window.location.hash.split("=")[1])  
//得到  /articaldetail/12

登录页面,需要判定url有无带值
但是没有值的时候也会是字符串’undefined’

if ( decodeURIComponent(window.location.hash.split("=")[1]) &&
	 // 这个有可能值为undefined 也不能跳转
	decodeURIComponent(window.location.hash.split("=")[1]) !=
	"undefined") 
	{
	console.log(decodeURIComponent(window.location.hash.split("=")[1])); 
	 // 没用decodeURIComponent转钱  /#/login?redirectURL=%2Farticaldetail%2F12
	 //  用decodeURIComponent转后 /articaldetail/12
     this.$router.push({
         path: decodeURIComponent(window.location.hash.split("=")[1]),
         });
 } else {
 		//没有带hash,我们直接跳到个人中心
      this.$router.push({ path: `/personal/${res.data.data.user.id}` });
 }

这样我们就能跳转到用户没有登录前的页面,增加用户体验

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值