路由守卫中的白名单

在写登录注册的路由守卫的时候,如果直接进行判断,会出现错误

router.beforeEach((to,from,next)=>{
  if(VueCookies.get("token")){
    next()
  }else{
    next("/login")
  }
})

 

 所以要在判断的时候添加白名单,
在路由守卫中使用白名单是一种常见的实践,允许你指定哪些路由是不需要进行权限检查的,用户可以在没有满足特定条件(例如登录)的情况下访问这些路由。这通常用于公共页面,如登录、注册、首页等。

const whiteList = ['/login', '/home', '/register'] // 白名单中的路由不需要权限即可访问

router.beforeEach((to, from, next) => {
  if (Vue.$cookies.get("token")) {
    // 用户已登录,放行
    next()
  } else {
    // 用户未登录,检查白名单
    if (whiteList.indexOf(to.path) !== -1) {
      // 在白名单中,放行
      next()
    } else {
      // 不在白名单中,重定向到登录页面
      next('/login')
    }
  }
})

 

// 检查
router.beforeEach((to, from, next) => {
  console.log('全局守卫', to.name);
  if (whiteList.includes(to.name)) {
    console.log('在白名单中', to.name);
    return next();
  }
  if (VueCookies.get("token")) {
    console.log('有Token', VueCookies.get("token"));
    next();
  } else if (to.path !== '/helloworld') {
    console.log('没有Token,重定向到 /helloworld');
    next('/helloworld');
  } else {
    console.log('已经在 /helloworld,无需重定向');
    next();
  }
});

 

posted @ 2023-10-27 11:02  瑞姆  阅读(114)  评论(0编辑  收藏  举报