Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  107] [ 5]  / answers: 1 / hits: 9080  / 3 Years ago, tue, february 2, 2021, 12:00:00

Here the router guard is working fine on my vue app, but after logging in, the following error appears on console.



Uncaught (in promise) Error: Redirected when going from "/login" to "/" via a navigation guard.



Here is my code snippet.


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"),
},
],
},
];


The Auth guard:


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();
}
});

Can't figure out the problem. Thanks in advance !


More From » vue.js

 Answers
14

Since next does not exit the guard, the guard will call next a minimum of 2 times per route because you have 2 separate if statements and both will run.



  • Change the // path to /

  • call next like return next to exit the function, or structure your if statements so that only one will run.

  • Set loggedIn inside the guard or it will only be evaluated once, when the router is created


Here's one way to do it that also covers routes having no 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();
});

[#1847] Thursday, January 28, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;