NextJS中GET类型App Route无法获取URL参数问题
问题描述
我在Next.js中创建了一个App Route,目录结构如下:
app/api/resthistoryserv/route.ts
前端通过以下代码发起请求:
const res = await fetch( `/api/resthistoryserv?client_id=${encodeURIComponent('ASDFASFDDFASD')}` );
实际请求URL为:/api/resthistoryserv?client_id=ASDFASFDDFASD
请求能正常发送,但后端API Route始终获取不到查询参数。
API Route代码:
export async function GET(request: NextRequest) { try { const searchParams = request.nextUrl.searchParams; console.log('nextUrl:', request.nextUrl); console.log('All received parameters:', Object.fromEntries(searchParams.entries())); console.log('CLIENTID', searchParams.get('client_id')); // 其他业务逻辑 } catch (error) { // 错误处理 } }
打印结果显示查询参数为空:
nextUrl: NextURL { [Symbol(NextURLInternal)]: { url: URL { href: 'https://localhost:3000/api/resthistoryserv', origin: 'https://localhost:3000', protocol: 'https:', username: '', password: '', host: 'localhost:3000', hostname: 'localhost', port: '3000', pathname: '/api/resthistoryserv', search: '', searchParams: URLSearchParams {}, hash: '' }, options: { headers: [Object], nextConfig: undefined }, basePath: '', domainLocale: undefined, defaultLocale: undefined, buildId: undefined, locale: undefined, trailingSlash: false } } All received parameters: {} CLIENT ID null
解决方法
1. 检查中间件是否丢失了查询参数
如果项目中有middleware.ts,排查是否在重写/转发请求时清空了查询参数。比如错误的重写规则会丢掉search部分,要确保重写时保留原有参数:
// middleware.ts 正确示例:保留查询参数 export function middleware(request: NextRequest) { const targetUrl = new URL('/api/resthistoryserv', request.url); // 保留原请求的查询参数 targetUrl.search = request.url.search; return NextResponse.redirect(targetUrl); }
2. 直接从原生URL对象解析参数
如果request.nextUrl出现异常,尝试用原生URL对象解析请求地址:
export async function GET(request: NextRequest) { try { const url = new URL(request.url); const clientId = url.searchParams.get('client_id'); console.log('CLIENTID', clientId); // 其他业务逻辑 } catch (error) { // 错误处理 } }
3. 升级Next.js版本
部分旧版本的Next.js在App Route处理查询参数时存在bug,建议升级到13.4及以上的稳定版本,大概率能解决这类兼容性问题。
4. 验证前端请求的实际参数
打开浏览器开发者工具的网络面板,查看发送的请求URL,确认client_id参数确实被携带。有时候前端字符串拼接出错(比如变量未赋值),会导致参数根本没发送出去。
内容的提问来源于stack exchange,提问作者Patricio
相关产品推荐
相关产品推荐

