A JSON API
Return JSON with the right header and status codes.
Example
const http = require("http");
const items = [{ id: 1, name: "pen" }];
const s = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
if (req.url === "/items") return res.end(JSON.stringify(items));
res.statusCode = 404; res.end(JSON.stringify({ error: "not found" }));
}).listen(0, async () => {
const base = "http://localhost:" + s.address().port;
console.log(await (await fetch(base + "/items")).json());
console.log((await fetch(base + "/x")).status);
s.close();
});Result
[ { id: 1, name: 'pen' } ]
404Exercise
JSON type.
"application/"
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.