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

Next.js App Router中API路由404时返回JSON响应的实现方案

解决Next.js App Router API未定义路由返回JSON 404的方案

方法1:使用Catch-All兜底API路由

在app/api目录下创建[...catchAll]/route.js(或.ts)文件,这个路由会匹配所有未显式定义的API路径,直接返回JSON格式的404响应,且优先级低于你已定义的正常API路由,不会影响现有接口。

示例代码:

// app/api/[...catchAll]/route.js
export async function GET() {
  return new Response(
    JSON.stringify({
      status: 404,
      error: "Not Found",
      message: "The requested API route does not exist."
    }),
    {
      status: 404,
      headers: {
        "Content-Type": "application/json"
      }
    }
  );
}

// 如需支持POST/PUT/DELETE等其他HTTP方法,导出对应处理函数即可
export async function POST() {
  return new Response(
    JSON.stringify({
      status: 404,
      error: "Not Found",
      message: "The requested API route does not exist."
    }),
    {
      status: 404,
      headers: {
        "Content-Type": "application/json"
      }
    }
  );
}

方法2:利用API目录下的全局错误处理

如果需要统一处理API路由的所有错误(包括404和其他服务器错误),可以在app/api目录下创建error.js文件:

// app/api/error.js
'use client'

export default function Error({ error }) {
  const is404 = error.status === 404 || error.message.includes('not found');
  
  const responseBody = JSON.stringify({
    status: is404 ? 404 : 500,
    error: is404 ? "Not Found" : "Internal Server Error",
    message: is404 ? "Requested API route does not exist." : "An unexpected error occurred."
  });

  return new Response(responseBody, {
    status: is404 ? 404 : 500,
    headers: {
      "Content-Type": "application/json"
    }
  });
}

注意:error.js必须添加'use client'指令,它会捕获该目录下所有API路由抛出的错误,包括未找到路由的场景。

补充说明

  • 两种方法可结合使用:用Catch-All路由专门处理未找到路由的情况,error.js处理其他API运行时错误。
  • 确保响应头的Content-Type设置为application/json,避免客户端解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:02:38