我有一个中间件在我的下一个应用程序,使它转换所有的网址(除了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
这个错误似乎不会影响我的应用程序,但我想知道为什么它会在那里,以及如何删除它。任何想法?
1条答案
按热度按时间wsxa1bj11#
出现此问题的原因是,在用户已导航到同一URL后尝试硬导航到该URL时发生
Invariant Violation
错误。要解决此问题,您可以创建一个配置对象,并将matcher属性设置为一个正则表达式数组,该数组匹配所有请求路径,但以下列字符开头的请求路径除外:
若要实现此解决方案,请将以下代码添加到项目中:
在Next.js中间件文档中找到的代码段。
最终代码如下所示: