Routing by Hand
Without a framework you read req.method and req.url and choose a handler. This shows what Express does for you.
Example
const http = require('node:http');
const routes = {
'GET /': () => ({ msg: 'home' }),
'GET /users': () => [{ id: 1 }],
};
const server = http.createServer((req, res) => {
const h = routes[`${req.method} ${req.url}`];
res.statusCode = h ? 200 : 404;
res.end(JSON.stringify(h ? h() : { error: 'not found' }));
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/', '/users', '/nope']) {
const r = await fetch(base + p);
console.log(p, r.status, await r.text());
}
server.close();
});Result
/ 200 {"msg":"home"}
/users 200 [{"id":1}]
/nope 404 {"error":"not found"}Exercise
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.