【问题标题】:Redirected when going from to via navigation guard从导航到导航时重定向
【发布时间】:2020-12-01 06:21:48
【问题描述】:

我正在尝试使用 Vue 路由器身份验证保护来保护我的 Vue 组件。
案例场景:未经身份验证的用户登陆主页(“/”路由),他试图访问“/profile”,但这是一个私有组件,所以他会被vue路由器重定向到“/auth/profile”,所以他将进行身份验证,然后 Auth 组件会将用户重定向到“/profile”组件,因为他在 URL 中获得了它的路径。

那是我的守护

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.private)) {
    if (!store.getters.getUser) {
      //console.log("PRIVATE - NOT authenticated");
      next({ path: "/auth" + `${to.path}` });
    } else {
      //console.log("PRIVATE - authenticated");
      next();
    }
  } else {
    //console.log("NOT PRIVATE");
    next();
  }
});

一切都按预期工作,但我收到一个错误,这很烦人

Redirected when going from "/" to "/profile" via a navigation guard.

【问题讨论】:

  • 似乎是一个错误,已在 3.3.1 版本中修复。否则尝试删除你的 node_modules 文件夹和 package-lock.json 文件并再次运行npm install
  • @gurumaxi 我刚试了,没用。
  • 您被多次重定向
  • 你没有做错什么,在这里查看我的回答stackoverflow.com/a/64808960/7662112
  • 这是@gurumaxi 谈论的关于3.3.1 错误修复的链接:github.com/vuejs/vue-router/blob/dev/…

标签: vue-router


【解决方案1】:

在您的代码中的某处,在被重定向到"/profile" 后,您将被重定向回"/"。这就是 vue-router 所抱怨的。

所以问题在于每个操作被重定向多次。

您需要确保每个导航操作只有一个重定向。

【讨论】:

  • 嗯,我不知道如何改变它。例如,如果一个未经身份验证的用户尝试访问/profile,那么他将被重定向到/auth/profile,因此应用程序会知道用户通过身份验证后,他将被重定向到/profile,因为这就是他正在尝试的访问。这就是我有双重重定向的原因。我应该如何实现呢?
【解决方案2】:

问题通过替换解决

 next({ name: "Onboarding" });

router.push({ path: 'Onboarding' });

【讨论】:

    【解决方案3】:

    将 vue-router 版本降低到3.0.7,或者 按照代码进入您的app.jsindex.js,您导入哪个vue-router 示例:

    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    const originalPush = VueRouter.prototype.push
    VueRouter.prototype.push = function push(location, onResolve, onReject) {undefined
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
    }
    
    Vue.use(VueRouter);
    ...
    
    #code
    

    【讨论】:

      猜你喜欢
      • 2012-06-14
      • 2015-09-20
      • 2018-09-14
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多