当前位置: 首页> 健康> 科研 > NEXT.js 中间件 NextResponse.redirect 无效

NEXT.js 中间件 NextResponse.redirect 无效

时间:2025/8/4 14:39:30来源:https://blog.csdn.net/weixin_44240581/article/details/142220306 浏览次数:0次

原代码

// src/middleware.js
import { NextResponse } from 'next/server'export function middleware(request) {handleLocale(request)
}// 处理国际化
const handleLocale = (request) => {const locales = ['zh_CN', 'en_US', 'ja_JP']const { pathname } = request.nextUrlconst pathnameHasLocale = locales.some(locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`)// 正确进入到匹配语言的目录,不做处理if (pathnameHasLocale) {// ...}// 没有进入到匹配的语言目录,设置默认语言,重定向到对应的语言目录else {const locale = locales[0]request.nextUrl.pathname = `/${locale}${pathname}`return NextResponse.redirect(request.nextUrl)}
}export const config = {// 中间件运行的路径matcher: [// NEXT.js内部资源路径 /_next// e.g. /_next/static/chunks/webpack.js |  /_next/static/chunks/main-app.js |  /_next/static/chunks/app-pages-internals.js// 不匹配内部资源,内容资源不需要国际化'/((?!_next|favicon.ico).*)',],
}

修改后


NextResponse.redirect 必须要在middleware 方法里执行,不然不生效


// src/middleware.js
export function middleware(request) {const localeStatus = handleLocale(request);if (localeStatus === 'locale redirect') {return NextResponse.redirect(request.nextUrl)}
}// 是否包含国际化的资源路径
const handleLocale = (request) => {const locales = ['zh_CN', 'en_US', 'ja_JP']const { pathname } = request.nextUrlconst pathnameHasLocale = locales.some(locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`)// 正确进入到匹配语言的目录,不做处理if (pathnameHasLocale) {return 'locale matched'}// 没有进入到匹配的语言目录,设置默认语言,重定向到对应的语言目录else {const locale = locales[0]request.nextUrl.pathname = `/${locale}${pathname}`return 'locale redirect'}
}
关键字:NEXT.js 中间件 NextResponse.redirect 无效

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: