I am trying out the new Route API's in Next v13.2, but cannot seem to figure out how to get the body values in a POST request.
On the client side, I am calling the API something like this:
const response = await fetch("/api/bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt: "Testing" }),
});
I then created a file in the app directory called route.js
I created the function for the POST request and tried fetching the values from the request object in numerous ways, with no luck.
Something like:
export async function POST(request) {
console.log("Request", request.body.prompt);
return new Response({ response: prompt });
}
I tried fetching the body values from the request objects, but nothing seems to work.
With Next.js 13.4 by sending the POST request like this:
const response = await fetch("/api/bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt: "Testing" }),
});
you can make the following to extract the body data:
import { NextResponse } from 'next/server'
export async function POST(req) {
const body = await req.json()
return NextResponse.json({prompt: body.prompt})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With