I'm trying to set some routes that users can and can't access in my application, but sometimes my browser freezes and it doesn't give me any error messages, so I don't know what I'm doing wrong.
In the first IF, I'm checking if the route needs auth to be true to access, if it's false, I send user to login page. Then I check the group user is in, if it fails, redirect to root page "/". And if none of these IFs statements is true, I just redirect to the page user wants to navigate to.
router.beforeEach((to, from, next) => {
const isAuth = localStorage.getItem("auth");
const userGroupRaw = localStorage.getItem("userData");
const accessGroup = to.meta.group;
let userGroup;
if (userGroupRaw) {
userGroup = JSON.parse(userGroupRaw).id_access;
}
if (to.matched.some((record) => record.meta.requiresAuth)) {
console.log("if1");
if (isAuth === "false") {
next({ path: "/login" });
}
if (
(accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
!userGroup
) {
next({ path: "/" });
}
next();
}
next();
});
export default router;
CodePudding user response:
As you're not using 'else' statements, you're calling next()
multiple times and hitting an infinite loop (as mentioned in the comments).
You can return
instead to stop the code at that point.
router.beforeEach((to, from, next) => {
const isAuth = localStorage.getItem("auth");
const userGroupRaw = localStorage.getItem("userData");
const accessGroup = to.meta.group;
let userGroup;
if (userGroupRaw) {
userGroup = JSON.parse(userGroupRaw).id_access;
}
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (isAuth === "false") {
return next({
path: "/login"
});
}
if (
(accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
!userGroup
) {
return next({
path: "/"
});
}
// next(); - this is not needed as the preceding next always gets called.
}
next();
})
export default router;
CodePudding user response:
The docs say "you must call next
exactly once" 1. If the the first if
is true, it's called twice. If the second or third if are true, it gets called three times.
You might need to return inside the if
s to avoid that. Or use else
statements.
I'm not 100% sure that's the issue, but it's where I'd start.
1: It also says that next
was supposed to be removed, according to this RFC, so I think returning is the way to go instead, anyway.