NextJS13中如何返回API响应状态?

Wal*_*med 16 typescript reactjs next.js next.js13

现在我使用不同的方法在 NextJS-13 中返回 API HTTP 状态,但似乎没有任何效果对我有用。

注意:我在我的项目中使用 Typescript。

这是我的代码,带有静态 200 API 响应,并在正文中发送 API 状态:

type postProps = {
  title: string;
  content?: string;
  published: boolean;
};

export async function POST(request: Request) {
  const post: postProps = await request.json();
  if (!post.title) {
    return NextResponse.json({
      status: 400,
      message: "Please enter title",
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我努力了

import type { NextApiRequest, NextApiResponse } from "next";

export async function POST(response: NextApiResponse, request: NextApiRequest ) {
  const post: postProps = await request.body;
  if (!post.title) {
    return response.status(400).json({
     message: "Please enter title"
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

But it give me TypeError: res.status is not a function

我也尝试过

import type { NextApiRequest, NextApiResponse } from "next";

export async function POST(response: Response, request: Request) {
  const post: postProps = await request.json();
  if (!post.title) {
    return response.status(400).json({
     message: "Please enter title"
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

But it give me the following error: This expression is not callable. Type 'Number' has no call signatures.

bra*_*nli 40

import { NextResponse } from "next/server";

NextResponse.json({
  message: "Please enter title"
}, {
  status: 400,
})
Run Code Online (Sandbox Code Playgroud)

  • 如何设置状态:204?出现错误。 (4认同)