next.js 中间件抛出错误“错误:固定变量:尝试硬导航到相同的URL”

fhity93d  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(156)

我有一个中间件在我的下一个应用程序,使它转换所有的网址(除了API路由)小写。

import { NextResponse } from "next/server";

const Middleware = (req) => {
  const {
    pathname,
    search,
    origin
  } = req.nextUrl;
  if (pathname.startsWith('/api') || pathname === pathname.toLowerCase())
    return NextResponse.next();

  return NextResponse.redirect(
    `${origin + pathname.toLowerCase() + search}`
  );
};

export default Middleware;

它能满足我的期望,但问题是在应用程序的所有页面中,我在控制台中收到一个错误:
未捕获(承诺中)错误:固定:尝试硬导航到相同的URL
这个错误似乎不会影响我的应用程序,但我想知道为什么它会在那里,以及如何删除它。任何想法?

wsxa1bj1

wsxa1bj11#

出现此问题的原因是,在用户已导航到同一URL后尝试硬导航到该URL时发生Invariant Violation错误。
要解决此问题,您可以创建一个配置对象,并将matcher属性设置为一个正则表达式数组,该数组匹配所有请求路径,但以下列字符开头的请求路径除外:

  • API(API途径)
  • _next/static(静态文件)
  • _next/image(图像优化文件)
  • 图标.ico(图标文件)

若要实现此解决方案,请将以下代码添加到项目中:

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}

在Next.js中间件文档中找到的代码段。
最终代码如下所示:

import { NextResponse } from "next/server";

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
    '/',
  ],
};

const Middleware = (req) => {
  const {
    pathname,
    search,
    origin
  } = req.nextUrl;
  if (pathname === pathname.toLowerCase())
    return NextResponse.next();

  return NextResponse.redirect(
    `${origin + pathname.toLowerCase() + search}`
  );
};

export default Middleware;

相关问题