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

Next.js API路由处理器中获取URL参数的方法

Next.js 13.4.16 App Router API路由获取动态[id]参数的方法

问题场景

我有一个客户端组件GetUserInfoButton,点击时向/api/users/[id]发送GET请求([id]为MongoDB风格的字母数字ID),现在需要在app/api/users/[id]/route.ts中接收并处理这个id参数。当前我通过分割URL的方式获取id,但这不是App Router的标准做法,想知道正确的参数获取方式。

客户端组件代码:

'use client';

export default function GetUserInfoButton({ id }: { id: string }) {
    const contentType = "application/json";
    const handleClick = async (id: string) => {
        try {
            const res = await fetch(`/api/users/${id}`, {
                method: "GET",
                headers: {
                    "Content-Type": contentType,
                }
            });
            if (!res.ok) {
                throw new Error(res.status.toString());
            }
        } catch (error) {
            console.log("error ===> ", error);
        }
    };

    return (
        <button onClick={() => handleClick(id)}>
            Get
        </button>
    );
}

当前route.ts代码(非标准写法):

import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
    const id = req.url.split("http://localhost:3000/api/users/")[1];
    return NextResponse.json({
        success: true,
        id: id
    }, {
        status: 200,
    })
}

解决方案

在App Router的API路由中,动态路由参数会作为函数的第二个参数直接传入,无需手动分割URL。修改后的route.ts代码如下:

import { NextResponse } from "next/server";

// 第二个参数params包含动态路由中的参数
export async function GET(_req: Request, { params }: { params: { id: string } }) {
    const { id } = params;
    return NextResponse.json({
        success: true,
        id: id
    }, {
        status: 200,
    })
}

说明

  • 如果不需要请求的其他信息,无需依赖NextRequest,用原生Request即可;保留NextRequest也完全兼容。
  • params对象会自动映射动态路由定义的参数,通过TS类型声明可以明确参数类型,避免类型错误。
  • 客户端组件的fetch请求写法是正确的,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:11:19