简体   繁体   English

带有重定向路由的Vue-Router无限循环

[英]Vue-Router infinite loop with redirect route

I'm trying to find the best way to redirect non-authenticated users to the login page/screen.我正在尝试找到将未经身份验证的用户重定向到登录页面/屏幕的最佳方法。 Currently I'm trying to catch authentication with JWT tokens in the route before loading components.目前,我正在尝试在加载组件之前在路由中使用 JWT 令牌进行身份验证。 However, I'm getting snagged on the router.beforEach() with an infinite loop:但是,我在router.beforEach()router.beforEach()了无限循环:

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requiresAuth)) {
    alert('needs auth!'); // used for testing
    if (localStorage.getItem('jwt') == null) {
      next('/login'); // here is where the infinite loop hits
    } else {
      next();
    }
  } else {
    next();
  }
});

When I reach a route that needs to be authenticated, the next('/login') call gets stuck in an infinite loop.当我到达需要验证的路由时, next('/login')调用陷入无限循环。 I can avoid this like so:我可以像这样避免这种情况:

if (to.path !== '/login') {
    next('/login');
} else {
    next();
  }

But that calls the alert twice and seems like an inefficient and/or hacky way to go about this.但这会调用两次警报,似乎是一种低效和/或笨拙的方法来解决这个问题。 Is there a better way to test for conditions for routes than this?有没有比这更好的方法来测试路线的条件? Thanks for any tips, advice, help感谢您的任何提示,建议,帮助

I don't think this is hacky.我不认为这是 hacky。

if (to.path !== '/login') {
    next('/login');
}

As you are changing the route, it will naturally trigger router.beforeEach again.当你改变路由时,它自然router.beforeEach再次触发router.beforeEach

You could move it above if (to.matched.some(r => r.meta.requiresAuth)) { to avoid doing that check unnecessarily with你可以把它移到上面if (to.matched.some(r => r.meta.requiresAuth)) {以避免做不必要的检查

if (to.path === '/login') {
    next();
}

An alternative is to jump out of the SPA with window.location , but I don't think that is better.另一种方法是使用window.location跳出SPA ,但我认为这不是更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM