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

如何修改NextJS API的404页面以返回JSON格式?

在NextJS 12.3.1中为不存在的API端点返回JSON格式404

在NextJS 12.3.1里,要让未定义的API路径返回指定JSON格式的404响应,有两种实用方案:

方案一:自定义API错误处理文件(Pages Router适用)

在pages/api目录下创建_error.js文件,它会捕获所有API路由的错误场景,包括404:

export default function handler(req, res) {
  if (res.statusCode === 404) {
    res.status(404).json({ error: "Resource not found" });
  } else {
    res.status(res.statusCode).json({ error: "An error occurred" });
  }
}

该文件仅作用于pages/api下的路由,不会影响页面路由的404表现。

方案二:使用中间件统一拦截(Pages Router适用)

在项目根目录创建middleware.js,通过拦截请求判断路径有效性,不匹配则返回JSON 404:

import { NextResponse } from 'next/server';

export function middleware(req) {
  const url = req.nextUrl;
  if (url.pathname.startsWith('/api')) {
    // 这里可根据实际业务扩展有效API路径规则
    const validApiPrefixes = ['/api/v1/modules'];
    const isValid = validApiPrefixes.some(prefix => url.pathname.startsWith(prefix));
    
    if (!isValid) {
      return new NextResponse(JSON.stringify({ error: "Resource not found" }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  }
  return NextResponse.next();
}

这种方式能统一管控所有API请求的404返回,灵活性更高。

注意事项

  • NextJS 12.3.1中App Router的API路由支持尚未完全稳定,建议优先采用Pages Router的方案。
  • 务必设置Content-Type为application/json,避免客户端解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:20:32