Browser becomes unresponsive when using beforeEach
P粉724256860
P粉724256860 2024-03-19 22:53:00
0
1
333

I'm trying to set up some routes in my application that users can and cannot access, but sometimes my browser freezes and won't give me any error messages, so I don't know what I'm doing wrong.

In the first IF, I check if the route requires authentication to true for access, if false, I send the user to the login page. I then check which group the user is in and if that fails, redirect to the root page "/". If none of these IF statements hold true, I just redirect to the page the 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;

P粉724256860
P粉724256860

reply all(1)
P粉409742142

Since you are not using an "else" statement, you are calling next() multiple times and getting stuck in an infinite loop (as mentioned in the comments).

You can use return to stop the code at this 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;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template