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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:34:55