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

为何在Next.js API路由中无法使用类型为NextResponse的res?

Why res.json() throws an error in Next.js App Router API routes

The error happens because of a core difference in how response handling works between Next.js's App Router (your current setup) and the older Pages Router:

  1. res in App Router isn't an Express-style response object
    In App Router API routes, when you receive res: NextResponse as a parameter, this is an immutable response instance—not the mutable, writable response stream used in Pages Router. The json() method on a NextResponse instance doesn't accept arguments (it’s not designed to send new data); the json() method you’re trying to use is actually the static method NextResponse.json(), which creates a new response object from your data.

  2. Wrong vs Correct Usage

    • Incorrect (triggers your error):
      export async function POST(req: NextRequest, res: NextResponse) {
        // Error: Expected 0 arguments, but got 2
        res.json({ message: "Success" }, { status: 200 });
      }
      
    • Correct (standard App Router pattern):
      import { NextRequest, NextResponse } from "next/server";
      
      export async function POST(req: NextRequest) {
        // Return a new NextResponse directly
        return NextResponse.json({ message: "Success" }, { status: 200 });
      }
      
    • If you need to modify an existing res instance (rare for most use cases), clone it with your desired changes:
      export async function POST(req: NextRequest, res: NextResponse) {
        return res.clone({
          body: JSON.stringify({ message: "Success" }),
          status: 200
        });
      }
      
  3. Key Takeaway
    App Router API routes are built to return response objects directly instead of mutating a res stream. The Express-style res.json(data) pattern only works in Pages Router; in App Router, use the static NextResponse.json() method to generate and return your JSON response.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:46:05