You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13中如何在route.ts的PATCH函数里获取postId路由参数?

在Next.js App Router API路由中获取动态参数postId

在App Router的API路由里,动态路由参数(比如[postId])不是通过请求对象的searchParams获取的,而是通过第二个上下文参数的params属性获取,你之前的函数参数定义有误,正确写法如下:

// PATCH api/posts/3
import { NextRequest, NextResponse } from 'next/server';

export const PATCH = async (req: NextRequest, { params }: { params: { postId: string } }) => {
  // 获取postId,类型为string,可根据需求转成number
  const postId = params.postId;
  
  // 后续逻辑,比如更新文章
  return NextResponse.json({ success: true, postId });
};

关键说明:

  • API路由的请求处理函数(如PATCH)的第二个参数是一个上下文对象,其中的params属性包含了所有动态路由参数。
  • req.nextUrl.searchParams仅用于获取URL中的查询参数(例如/api/posts?postId=3这种格式的参数),不适用动态路由参数。

内容的提问来源于stack exchange,提问作者Tajmirul Islam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:15:58