Routing by Hand
Check req.method and req.url to decide what to send.
Example
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/" ) return res.end("home");
if (req.url === "/api" && req.method === "GET") { res.setHeader("Content-Type", "application/json"); return res.end(JSON.stringify({ ok: true })); }
res.statusCode = 404; res.end("not found");
});
server.listen(0, async () => {
const base = "http://localhost:" + server.address().port;
for (const p of ["/", "/api", "/x"]) { const r = await fetch(base + p); console.log(p, r.status, await r.text()); }
server.close();
});Result
/ 200 home
/api 200 {"ok":true}
/x 404 not foundExercise
Not found status.
res.statusCode = Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.