Next.js Route API - Getting Body Values

Leo*_*Zyl 2 javascript next.js

我正在尝试 Next v13.2 中的新 Route API,但似乎无法弄清楚如何获取 POST 请求中的正文值。

在客户端,我调用 API 的方式如下:

      const response = await fetch("/api/bot", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt: "Testing" }),
      });
Run Code Online (Sandbox Code Playgroud)

然后我在应用程序目录中创建了一个名为route.js的文件

我为 POST 请求创建了函数,并尝试以多种方式从请求对象中获取值,但没有成功。

就像是:

export async function POST(request) {
  console.log("Request", request.body.prompt);
  return new Response({ response: prompt });
}
Run Code Online (Sandbox Code Playgroud)

我尝试从请求对象中获取正文值,但似乎没有任何效果。

小智 5

Next.js 13.4中,通过发送如下 POST 请求:

const response = await fetch("/api/bot", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt: "Testing" }),
      });
Run Code Online (Sandbox Code Playgroud)

您可以执行以下操作来提取身体数据:

import { NextResponse } from 'next/server'

export async function POST(req) {
  const body = await req.json()
  return NextResponse.json({prompt: body.prompt})
}
Run Code Online (Sandbox Code Playgroud)