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

Next.js报错:Cannot read properties of undefined (reading 'headers') 求助

问题原因分析

这个错误的核心原因是:Next.js App Router的路由处理函数必须返回一个NextResponse或标准Response实例,而你的POST函数在catch块中,当后端返回400错误时,只执行了日志打印,没有返回任何响应。Next.js内部尝试处理返回值时,发现是undefined,进而尝试读取其headers属性,最终抛出Cannot read properties of undefined (reading 'headers')错误。

修复方案

修改route.js的catch逻辑,确保无论哪种错误情况,都返回一个合法的NextResponse:

import axios from "axios";
import { NextResponse } from "next/server";

export async function POST(request) {
  const body = await request.json();

  try {
    const config = {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    };

    const response = await axios.post(
      "http://127.0.0.1:8000/app_api/login_user/",
      body,
      config
    );

    const data = response.data;
    const nextResponse = new NextResponse(JSON.stringify(data), {
      status: 200,
    });
    const { token } = data;
    nextResponse.cookies.set("token", token, { httpOnly: true, path: "/" });
    return nextResponse;
  } catch (error) {
    // 处理后端返回的错误响应(如400、401等)
    if (error.response) {
      const errorData = error.response.data;
      return new NextResponse(JSON.stringify(errorData), {
        status: error.response.status,
        headers: { "Content-Type": "application/json" },
      });
    } 
    // 处理网络错误等无响应的情况
    else {
      return new NextResponse(JSON.stringify({
        error: "Network error",
        message: "Failed to connect to server"
      }), {
        status: 500,
        headers: { "Content-Type": "application/json" },
      });
    }
  }
}
关键修改点
  • 确保catch块的所有分支都返回NextResponse实例,避免返回undefined
  • 保留后端返回的错误状态码和数据,让前端能正确接收并处理错误信息
  • 增加网络错误的兜底处理,覆盖所有可能的异常场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:40:12