Next is REST
Now I'm learning how to make REST API in Next.js
It turns out that you have to create route.js/.ts file somewhere in your app folder (even in some deep folder). So it's somewhat like page.jsx/.tsx.
In this file you have to export functions that are called same as HTTP method. So if you want to handle POST method, you have to export POST function.
And it's pretty easy e.g.
import { NextResponse } from 'next/server';
export async function POST(request) {
const d = await request.json();
return NextResponse.json({ok: true, d});
}
first I coded something like that:
const d = await request.json();
return NextResponse.json({ok: true, d: await request.json()});
but this generated error
- error TypeError: disturbed
at NextRequest.blob (node:internal/deps/undici/undici:1795:21)
at NextRequest.text (node:internal/deps/undici/undici:1813:33)
at NextRequest.json (node:internal/deps/undici/undici:1817:38)
It turns out that you shouldn't call .json() method twice, or you'll see an error
front-end part is pretty straightforward
'use client';
export function Form() {
const handleSubmit = async (e) => {
e.preventDefault();
const fd = new FormData(e.target);
const r = await fetch('/components', {
method: 'POST',
body: JSON.stringify(Object.fromEntries(fd.entries())),
headers: {
'Content-Type': 'application/json',
}
}).then(r => r.json());
console.log("RESULT =", r);
};
return <form onSubmit={handleSubmit} action="/components" method="POST">
<input type="text" name="kot" />
<input type="submit"/>
</form>
}
Notice that it is similar to my previous example when I was fetching form to Expresss.js from HTML.
Comments
Post a Comment