IT이야기

내비게이션 가드를 통해 "/로그인"에서 "/"로 이동할 때 리디렉션됨"이 나타나는 이유는?

cyworld 2022. 4. 10. 22:15
반응형

내비게이션 가드를 통해 "/로그인"에서 "/"로 이동할 때 리디렉션됨"이 나타나는 이유는?

여기서 라우터 가드는 내 vue 앱에서 잘 작동하고 있지만 로그인 후 콘솔에 다음과 같은 오류가 나타난다.

검색되지 않은(약속 중) 오류: 내비게이션 가드를 통해 "/로그인"에서 "/"로 이동할 때 리디렉션됨.

여기 내 코드 조각이 있다.

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개의 도기 이상if진술과 두 진술 모두 실행될 것이다.

  • 변경하기//로 가는 길./
  • 부르다next맘에 들다return 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();
});

참조URL: https://stackoverflow.com/questions/66010046/why-redirected-when-going-from-login-to-via-a-navigation-guard-is-appe

반응형