Code
nodejs
import { createServer } from "http";
const server = createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
res.setHeader("Content-Type", "application/json");
if (req.method === "GET" && url.pathname === "/api/users") {
res.end(JSON.stringify([{ id: 1, name: "Alice" }]));
return;
}
if (req.method === "POST" && url.pathname === "/api/users") {
const body = await readBody(req);
res.statusCode = 201;
res.end(JSON.stringify({ created: body }));
return;
}
res.statusCode = 404;
res.end(JSON.stringify({ error: "Not found" }));
});
function readBody(req) {
return new Promise(resolve => {
let data = "";
req.on("data", chunk => (data += chunk));
req.on("end", () => resolve(JSON.parse(data || "{}")));
});
}
server.listen(3000, () => console.log("listening on :3000"));