vue-router — 未捕获(承诺)错误:重定向自“/login";到“/"通过导航卫士 [英] vue-router — Uncaught (in promise) Error: Redirected from "/login" to "/" via a navigation guard

查看:91
本文介绍了vue-router — 未捕获(承诺)错误:重定向自“/login";到“/"通过导航卫士的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 vue-router 给我这个错误?需要明确的是,登录流程按预期工作,但我想 a) 摆脱错误和 b) 了解错误发生的原因.

Why is vue-router giving me this error? To be clear, the login flow works as intended but I want to a) get rid of the errro and b) understand why the error is happening.

错误:

未捕获(承诺)错误:重定向自/login";到/"通过导航守卫.

登录流程

  1. 开始注销,但输入需要身份验证的 URL(即除/login"之外的任何内容)
  2. 被重定向到/login";(正如预期的那样).
  3. 登录
  4. 成功重定向到从第 1 步开始的 Url,除非出现上述错误.

登录操作:

doLogin({ commit }, loginData) {
  commit("loginStart");
  axiosClient
    .post("/jwt-auth/v1/token", {
      username: loginData.username,
      password: loginData.password,
    })
    .then((response) => {
      commit("loginStop", null);
      commit("setUserData", response.data);
      this.categories = airtableQuery.getTable("Categories");
      commit("setCategories", this.categories);
      this.locations = airtableQuery.getTable("Locations");
      commit("setLocations", this.locations);
      router.push("/"); // push to site root after authentication
    })
    .catch((error) => {
      console.log(error.response.data.message);
      commit("loginStop", error.response.data.message);
      commit("delUserData");
    });
},

路由器:

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: { requiresAuth: false },
  },
  {
    path: "/",
    name: "Home",
    component: Home,
    meta: { requiresAuth: true },
  },
];

let entryUrl = null;
router.beforeEach((to, from, next) => {
  let localStorageUserData = JSON.parse(localStorage.getItem("userData"));
  let storeUserData = state.getters.getUserData;
  let userData = localStorageUserData || storeUserData;
  let isAuthenticated = userData.token !== "" && userData.token !== undefined;
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      if (to.name !== "Login" && to.name !== "Home") {
        entryUrl = to.fullPath;
      }
      next({ name: "Login" });
    } else if (entryUrl) {
      let url = entryUrl;
      entryUrl = null;
      next(url);
    } else {
      next();
    }
  } else {
    next();
  }
});

推荐答案

错误信息在 vue-router 的下一版本中得到更新.错误将显示为:

The error message is getting updated in the next version of vue-router. The error will read:

通过导航守卫从/login"转到/"时重定向

在您的代码中的某处,在被重定向到/login"之后,您正在重定向回/".和 vue-router 抱怨.您需要确保每个导航操作只有一个重定向.

Somewhere in your code, after being redirected to "/login", you are redirecting back to "/". And vue-router is complaining about. You'll want to make sure you only have one redirect per navigation action.

这篇关于vue-router — 未捕获(承诺)错误:重定向自“/login";到“/"通过导航卫士的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆