Next.js App Router出现Cannot read properties of undefined (reading 'headers')错误
Next.js POST接口报错:TypeError: Cannot read properties of undefined (reading 'headers')
问题根源
你遇到的错误是因为Next.js App Router要求路由处理函数必须返回一个有效的HTTP响应对象。你的原POST函数只执行了console.log但没有返回任何值,框架尝试读取响应的headers属性时,发现返回值为undefined,因此抛出了该错误。
修复代码
只需要给POST函数添加响应返回逻辑即可,示例如下:
import { NextResponse } from 'next/server'; export const POST = (req: Request) => { console.log('hello world'); // 返回一个JSON响应,也可以根据需求返回其他类型响应 return NextResponse.json({ message: '请求已处理' }, { status: 200 }); };
补充说明
如果不需要返回具体数据,也可以返回一个无内容的响应:
export const POST = (req: Request) => { console.log('hello world'); return new Response(null, { status: 204 }); };
你之前参考的errorResponse函数是用于错误场景的响应封装,但核心问题还是路由函数缺少返回值,先确保基础的响应返回逻辑正确,再集成错误处理逻辑即可。
内容的提问来源于stack exchange,提问作者Kunal Gaur
相关产品推荐
相关产品推荐

