Next.js中URL重写后如何获取国家代码查询参数?
解决Next.js Rewrite保留国家代码参数的问题
当前你的rewrite配置会丢弃countryCode路径参数,因为目标路径里没有对这个参数做传递处理。要让页面能拿到国家代码参数,你需要在重写规则里显式把countryCode传递到目标路径,具体有两种常用方式:
方式一:通过查询参数传递(URL可见)
修改rewrite规则,把countryCode作为查询参数附加到目标路径后:
{ source: '/:countryCode(\\w{1,2})/:category/:genre', // 这里把countryCode转成小写的countrycode参数,匹配你预期的参数名 destination: '/:category/:genre?countrycode=:countryCode', }
配置后访问http://localhost:8000/uk/theatre/broadway/,页面就能通过以下方式获取参数:
- Pages Router:使用
useRouter()钩子import { useRouter } from 'next/router'; export default function GenrePage() { const router = useRouter(); const { countrycode, category, genre } = router.query; // 可自行转成大写格式 return <div>国家代码:{countrycode?.toUpperCase()}</div>; } - App Router:通过页面组件的
searchParams参数获取export default function GenrePage({ params, searchParams }) { const countrycode = searchParams.countrycode?.toUpperCase(); const { category, genre } = params; return <div>国家代码:{countrycode}</div>; }
方式二:通过Middleware隐式传递(URL不可见)
如果你不想在URL里显示查询参数,可以用Next.js的Middleware拦截请求,把国家代码存入请求头后传递给页面:
- 在项目根目录创建
middleware.js文件:
import { NextResponse } from 'next/server'; export function middleware(request) { const url = request.nextUrl; // 匹配带国家代码的路径格式 const match = url.pathname.match(/^\/(\w{1,2})\/([^\/]+)\/([^\/]+)/); if (match) { const [_, countryCode, category, genre] = match; // 重写路径到不带国家代码的格式 url.pathname = `/${category}/${genre}`; // 把国家代码存入自定义请求头 const response = NextResponse.rewrite(url); response.headers.set('x-country-code', countryCode.toUpperCase()); return response; } return NextResponse.next(); } // 指定要匹配的路径规则 export const config = { matcher: '/:countryCode(\\w{1,2})/:category/:genre', };
- 在页面中获取请求头的国家代码:
- App Router:使用
headers()函数import { headers } from 'next/headers'; export default async function GenrePage({ params }) { const headersList = headers(); const countrycode = headersList.get('x-country-code'); const { category, genre } = params; return <div>国家代码:{countrycode}</div>; } - Pages Router:在
getServerSideProps中获取export async function getServerSideProps(context) { const countrycode = context.req.headers['x-country-code']; const { category, genre } = context.params; return { props: { countrycode, category, genre }, }; } export default function GenrePage({ countrycode, category, genre }) { return <div>国家代码:{countrycode}</div>; }
两种方式对比:方式一配置简单,适合不需要隐藏参数的场景;方式二不会暴露参数在URL中,适合对URL美观有要求的场景。
内容的提问来源于stack exchange,提问作者Ajith Arasu
相关产品推荐
相关产品推荐

