Vue-Router: 在导航守卫中检测到无限重定向,从”/”到”/login”。

huangapple go评论56阅读模式
英文:

Vue-Router: Detected an infinite redirection in a navigation guard when going from "/" to "/login"

问题

我想要阻止页面访问,如果没有身份验证令牌,然后重定向到登录页面。
我有两个.ts页面(主页和路由)

路由:

import { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/login/',
    name: 'Login',
    component: () => import('layouts/LoginLayout.vue')
  },

  {
    path: '/',
    component: () => import('layouts/DVRLayout.vue'),
    children: [
      { path: 'dashboard', component: () => import('pages/DashboardPage.vue') },
      { path: 'settings', component: () => import('pages/AppSettings.vue') },
    ],
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];
export default routes;

主页:

import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import routes from './routes';

export default route(function () {

  const Router = createRouter({ routes });
  
  Router.beforeResolve(async(to, from, next) => {
    if(!document.cookie){
      next('/login')
    } else {
      next('/')
    }

  })
  return Router;
});

在加载页面地址为localhost/#/时,它立即尝试重定向到/login并出现错误:

*[警告] [Vue Router警告]: 检测到导航守卫中的无限重定向,从“/”到“/login”。为避免堆栈溢出而中止。如果不修复,这将在生产环境中出现问题。(vue-router.js,第43行)

启动路由时出现意外错误:
错误:导航守卫中的无限重定向
(匿名函数) — vue-router.mjs:3178*

英文:

I want to block pages if there is no authentication token and redirect to login page.
I've got two .ts pages (main and routes)

routes:

import { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/login/',
    name: 'Login',
    component: () => import('layouts/LoginLayout.vue')
  },

  {
    path: '/',
    component: () => import('layouts/DVRLayout.vue'),
    children: [
      { path: 'dashboard', component: () => import('pages/DashboardPage.vue') },
      { path: 'settings', component: () => import('pages/AppSettings.vue')},
    ],
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];
export default routes;

main

import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import routes from './routes';


export default route(function () {

  const Router = createRouter({ routes });
  
  Router.beforeResolve(async(to, from, next) => {
    if(!document.cookie){
      next('/login')
    } else {
      next('/')
    }

  })
  return Router;
});

On load page address is localhost/#/, then it immediately try to redirect to /login and error appears:

*[Warning] [Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/login". Aborting to avoid a Stack Overflow. This will break in production if not fixed. (vue-router.js, line 43)

Unexpected error when starting the router:
Error: Infinite redirect in navigation guard
(anonymous function) — vue-router.mjs:3178*

答案1

得分: 4

Router.beforeResolve 在每次导航之前运行,即使是由守卫自身发起的导航也是如此。首次重定向到 /login 会启动新的导航,因此守卫再次激活,!document.cookie 仍然为真,因此会再次重定向到 /login,如此循环。

else { next('/') } 也可能不是您想要的。这意味着无论用户尝试导航到哪里,只要 !document.cookie 为假,都会将它们重定向到 "/"。我认为您只是想调用 next(),这意味着"继续当前的导航,无论目标是什么"。

尝试:

Router.beforeResolve(async (to, from, next) => {
  if (!document.cookie && to.path !== '/login') {
    next('/login');
  } else {
    next();
  }
});
英文:

Router.beforeResolve runs before every navigation, even navigations initiated by the guard itself. The first redirect to /login starts a new navigation so the guard activates again and !document.cookie is still true so it redirects again to /login and this repeats forever.

The else { next('/') } is also probably not what you want. It means no matter where the user tries to navigate, as long as !document.cookie is false, always direct them to "/". I think you just mean to call next() which means "continue with the current navigation, wherever that may be"

Try

Router.beforeResolve(async (to, from, next) => {
  if (!document.cookie && to.path !== '/login') {
    next('/login');
  } else {
    next();
  }
});

huangapple
  • 本文由 发表于 2023年4月6日 22:33:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定