Next.js 13中如何正确返回API响应状态?(TypeScript环境)
Next.js 13(TypeScript)API正确返回HTTP状态码的方法
你之前的写法错误核心是混淆了Next.js 13 App Router 和传统 Pages Router 的API编写规则,以下是对应场景的正确实现:
一、App Router 场景(Next.js 13默认目录结构)
App Router下的API文件需命名为route.ts,通过NextResponse的配置参数设置HTTP状态码:
import { NextResponse } from 'next/server'; type postProps = { title: string; content?: string; published: boolean; }; export async function POST(request: Request) { const post: postProps = await request.json(); if (!post.title) { // 第二个参数配置HTTP状态码 return NextResponse.json( { message: "Please enter title" }, { status: 400 } ); } // 成功场景返回200状态码 return NextResponse.json( { message: "Post created successfully", post }, { status: 200 } ); }
你之前的错误原因:
- 第一个写法仅在响应体中添加了
status字段,但实际HTTP状态码仍为默认的200,需通过NextResponse.json的第二个配置参数设置真实状态码。 - 第二个写法误用了Pages Router的
NextApiRequest/NextApiResponse类型,且参数顺序颠倒(Pages Router中是req在前,res在后),但App Router的API函数仅接收Request参数,不支持这种写法。 - 第三个写法使用了原生
Response对象,但原生Response的status是只读属性,不能通过status()方法调用,需通过构造函数参数设置。
可选:使用原生Response的写法
type postProps = { title: string; content?: string; published: boolean; }; export async function POST(request: Request) { const post: postProps = await request.json(); if (!post.title) { return new Response( JSON.stringify({ message: "Please enter title" }), { status: 400, headers: { "Content-Type": "application/json" } } ); } return new Response( JSON.stringify({ message: "Post created successfully", post }), { status: 200 } ); }
二、Pages Router 场景(传统pages/api目录)
若你的项目仍使用Pages Router,API文件需放在pages/api目录下,写法如下:
import type { NextApiRequest, NextApiResponse } from "next"; type postProps = { title: string; content?: string; published: boolean; }; export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { const post: postProps = req.body; if (!post.title) { return res.status(400).json({ message: "Please enter title" }); } res.status(200).json({ message: "Post created successfully", post }); } else { res.setHeader('Allow', ['POST']); res.status(405).end(`Method ${req.method} Not Allowed`); } }
内容的提问来源于stack exchange,提问作者Wali Amed
相关产品推荐
相关产品推荐

