Nuxt 3 中间件往返路由始终相同

问题描述 投票:0回答:1

我在 Nuxt 3 应用程序中面临一个奇怪的问题。我确实想将我的第一个中间件添加到我的项目中,名为

auth.ts
。该中间件应该保护某些页面免受未登录用户的访问。基本上,它应该向已登录的用户授予对所请求页面的访问权限,并将未登录的用户导航到登录页面。非常简单直接。

但是,我的中间件中的

to
from
变量始终相同。这会导致
infinite redirection in a navigation guard

这是我的中间件:

export default defineNuxtRouteMiddleware((to, from) => {
    const userStore = useUserStore();

    console.log('From auth middleware')
    console.log('to', to)
    console.log('from', from)
    console.log('authenticated', userStore.authenticated)

    // If the user is authenticated, continue to the requested route
    if (userStore.authenticated === true) {
        return navigateTo(to.fullPath);
    }

    // If the user is not authenticated, redirect to the login page
        return navigateTo('/login');
    })

authenticated
变量来自我的 Pinia 商店。

这就是我将中间件添加到我的

/profile
页面的方法:

definePageMeta({ middleware: ["auth"] });

这是我得到的错误:

[Vue Router warn]: Detected a possibly infinite redirection in a navigation guard when going from "/profile" to "/profile". Aborting to avoid a Stack Overflow. Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.

这是我从我的

auth.ts
中间件获得的控制台日志:

From auth middleware auth.ts:4:9

to Object { fullPath: "/profile", hash: "", query: {}, name: "profile", path: "/profile", params: {}, matched: (1) […], meta: Proxy, redirectedFrom: {…}, href: "/profile" } auth.ts:5:9

from Object { fullPath: "/profile ", path: "/profile", query: {}, hash: "", name: "profile", params: {}, matched: (1) […], meta: {…}, redirectedFrom: undefined, href: "/profile " } auth.ts:6:9

authenticated true

当用户未通过身份验证时,它会成功将用户导航到

/login
页面。但是当用户登录时我总是收到错误。如果我已经在个人资料页面上然后刷新页面,这对我来说是有意义的。

但是当我位于

/
并导航到
/profile
页面时,我也会收到此错误。但是当我从
from
页面导航到
/profile
页面时,
/
变量怎么会是
/profile
呢?

亲切的问候

javascript vue.js nuxt.js middleware
1个回答
0
投票

这只是因为当它通过身份验证时,您不会继续使用中间件,而是重定向到当前路由的新实例,该实例将运行新的中间件。要修复它,您不应该返回任何内容:

export default defineNuxtRouteMiddleware((to, from) => {
  const userStore = useUserStore();

  console.log("From auth middleware");
  console.log("to", to);
  console.log("from", from);
  console.log("authenticated", userStore.authenticated);

  // If the user is authenticated, continue to the requested route
  if (userStore.authenticated === true) {
    return // returns nothing means continue the middleware, instead of redirect again
  }

  // If the user is not authenticated, redirect to the login page
  return navigateTo("/login");
});
© www.soinside.com 2019 - 2024. All rights reserved.