Vue-Router:从“/”转到“/login”时在导航防护中检测到无限重定向

Ale*_*len 2 javascript redirect vue.js vue-router

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

\n

路线:

\n
import { RouteRecordRaw } from 'vue-router';\nconst routes: RouteRecordRaw[] = [\n  {\n    path: '/login/',\n    name: 'Login',\n    component: () => import('layouts/LoginLayout.vue')\n  },\n\n  {\n    path: '/',\n    component: () => import('layouts/DVRLayout.vue'),\n    children: [\n      { path: 'dashboard', component: () => import('pages/DashboardPage.vue') },\n      { path: 'settings', component: () => import('pages/AppSettings.vue')},\n    ],\n  },\n\n  {\n    path: '/:catchAll(.*)*',\n    component: () => import('pages/ErrorNotFound.vue'),\n  },\n];\nexport default routes;\n
Run Code Online (Sandbox Code Playgroud)\n

主要的

\n
import {\n  createMemoryHistory,\n  createRouter,\n  createWebHashHistory,\n  createWebHistory,\n} from 'vue-router';\n\nimport routes from './routes';\n\n\nexport default route(function () {\n\n  const Router = createRouter({ routes });\n  \n  Router.beforeResolve(async(to, from, next) => {\n    if(!document.cookie){\n      next('/login')\n    } else {\n      next('/')\n    }\n\n  })\n  return Router;\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

*[警告] [Vue Router warn]:从“/”转到“/login”时,在导航防护中检测到无限重定向。中止以避免堆栈溢出。如果不修复,这将导致生产中断。(vue-router.js,第 43 行)

\n

启动路由器时出现意外错误:\n错误:导航防护中无限重定向\n(匿名函数)\xe2\x80\x94 vue-router.mjs:3178*

\n

yod*_*duh 5

Router.beforeResolve在每次导航之前运行,甚至是由守卫本身发起的导航。第一个重定向/login开始新的导航,因此防护再次激活并且!document.cookie仍然有效,因此它再次重定向到/login并且永远重复。

else { next('/') }也可能不是您想要的。这意味着无论用户尝试导航到哪里,只要为!document.cookiefalse,就始终将他们引导至“ /”。我想你只是想打电话next(),这意味着“继续当前的导航,无论它在哪里”

尝试

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