Of all the changes from Next.js 12 to 13, this is the most confusing. I have to look it up every time I want to make a fetch request because of all this JSON confusion. Can someone PLEASE help me once and for all?
I make a fetch POST request to the API handler like so:
//client component
const res = await fetch('/api/dostuff', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({dataObj: {hey: "ho"})
})
//PLEASE HELP ME GET THE RESPONSE
I receive it like so:
//route.js in api/dostuff/
export async function POST(request) {
const { dataObj } = await request.json()
//PLEASE HELP ME RETURN THIS
}
I've tried like a hundred different variations between all the ultra-confusing json methods (JSON.stringify
, JSON.parse
, and the extra confusing json()
), but nothing works. In Next.js 12 I didn't have to type the word "json" once.
You can return plain text using the Response
constructor:
// api/route.js
export async function POST(request) {
return new Response("Hello, Next.js!", {
status: 200,
});
}
Or return JSON, using NextResponse
from "next/server"
:
// api/route.js
import { NextResponse } from "next/server";
export async function POST(request) {
return NextResponse.json({ message: "Succes" });
}
And consume the response on the client:
const res = await fetch("/api/dostuff", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ dataObj: { hey: "ho" } }),
});
// For the first example (sending plain text):
const data = await res.text();
// For the second one (sending a JSON):
const data = await res.json();
For more, check out Route Handlers.
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