javascript - 为什么“通过导航守卫从“/login”转到“/”时重定向。” 正在出现?
问题描述
在这里,路由器保护在我的 vue 应用程序上工作正常,但登录后,控制台上出现以下错误。
未捕获(承诺)错误:通过导航守卫从“/login”转到“/”时重定向。
这是我的代码片段。
const routes = [
{
path: "/login",
component: () => import("../views/Auth/Login"),
meta: { hideForAuth: true },
},
{
path: "/",
component: DashboardLayout,
meta: { requiresAuth: true },
children: [
{
path: "home",
name: "Home",
component: () => import("../views/Home"),
},
],
},
];
Auth 守卫:
const loggedIn = localStorage.getItem("auth");
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!loggedIn) {
next({ path: "/login" });
} else {
next();
}
} else {
next();
}
if (to.matched.some((record) => record.meta.hideForAuth)) {
if (loggedIn) {
next({ path: "//" });
} else {
next();
}
} else {
next();
}
});
无法弄清楚问题所在。提前致谢 !
解决方案
由于next
不退出守卫,守卫将next
在每条路线上至少调用 2 次,因为您有 2 条单独的if
语句并且两者都会运行。
//
将路径更改为/
- call
next
likereturn next
退出函数,或者构造你的if
语句,以便只有一个会运行。 - 设置
loggedIn
在守卫内部,否则只会在创建路由器时评估一次
这是一种方法,它也涵盖了没有的路线meta
:
router.beforeEach((to, from, next) => {
const loggedIn = localStorage.getItem("auth");
const isAuth = to.matched.some((record) => record.meta.requiresAuth);
const isHide = to.matched.some((record) => record.meta.hideForAuth);
if (isAuth && !loggedIn) {
return next({ path: "/login" });
} else if (isHide && loggedIn) {
return next({ path: "/" });
}
next();
});
推荐阅读
- angular - 如何使用 Ionic Twitter Connect 插件发布推文
- file - awk:如果其他字段匹配值,则打印字段范围
- javascript - 如何制作交互式代码?
- javascript - Chrome 开发工具的奇怪行为无缘无故地从元素随机切换到源
- javascript - 如何使用属于 product_category 的选项设置订单
- unit-testing - 如何对 Sitecore MVC 中的方法进行单元测试,该方法对两个不同的 Sitecore 上下文具有紧密耦合的依赖关系?
- c# - 实体类型“订单”上的属性“myFk”具有临时值
- sql-server - 将多行合并为具有多列的一行
- python - 按条件对系列切片数据集
- ruby-on-rails - 如何在 FastJson API 中使用 CollectionSerializer?