A JSON REST Handler
A REST API maps HTTP methods to actions: GET reads, POST creates, PUT updates and DELETE removes. Read the body as a stream, then parse it.
Example
const http = require('node:http');
const items = [];
const server = http.createServer(async (req, res) => {
if (req.method === 'POST') {
let body = '';
for await (const c of req) body += c;
items.push(JSON.parse(body));
res.statusCode = 201;
return res.end(JSON.stringify({ count: items.length }));
}
res.end(JSON.stringify(items));
});
server.listen(0, async () => {
const url = `http://localhost:${server.address().port}`;
let r = await fetch(url, { method: 'POST', body: JSON.stringify({ name: 'pen' }) });
console.log(r.status, await r.json());
console.log(await (await fetch(url)).json());
server.close();
});Result
201 { count: 1 }
[ { name: 'pen' } ]Exercise
Status for created.
res.statusCode = Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.