Next.js 13.2 API调用无法访问请求体,报错request.json不是函数
Next.js 13.2 API路由报错TypeError: request.json is not a function
问题详情
客户端组件发起POST请求到/api/generate,API路由中调用request.json()时报错TypeError: request.json is not a function,打印request对象得到{ params: {}, searchParams: {} }。
环境:Next.js 13.2、Node.js 20,请求来自客户端组件。
客户端组件请求代码
const handleApiCall = async () => { const requestOptions = { method: "POST", body: JSON.stringify({ hello: "world" }), headers: { "content-type": "application/json" }, }; try { await fetch("/api/generate", requestOptions) .then((res) => res.json()) .then((data) => console.log(data)) .catch((err) => console.log(err)); } catch (error) { console.error("Error fetching data:", error); } };
原API路由代码
export default async function POST(request) { const res = await request.json(); console.log({ res }); }
解决方案
核心问题:API路由文件结构错误
Next.js 13.2的App Router模式下,API路由必须严格遵循以下结构:
- 创建
app/api/generate目录 - 在该目录下创建
route.js文件(文件名必须为route.js,不能自定义)
修正后的API路由代码
同时需要返回合法响应,否则客户端fetch会因无响应报错:
import { NextResponse } from 'next/server'; export async function POST(request) { const res = await request.json(); console.log({ res }); // 返回响应给客户端 return NextResponse.json({ received: res }); }
原因说明
如果API路由文件未命名为route.js(比如直接把generate.js放在app/api下),Next.js会将其识别为App Router的页面组件,此时POST函数的参数是页面的props(包含params和searchParams),而非请求对象,因此不存在json()方法,导致报错。
内容的提问来源于stack exchange,提问作者Reikon
相关产品推荐
相关产品推荐

