const http = require("node:http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ path: req.url }));
});
server.listen(3000);
http.createServer((req, res) => { ... }) creates a server. It calls your function for every request. server.listen(3000) starts it.
req is a readable stream. It holds the method, URL and headers.
res is a writable stream. You set the status and headers with res.writeHead or res.statusCode. Then you write the body and call res.end().
Everything else you must do by hand:
- Routing, by parsing
req.url - Reading the body from the stream and parsing it
- Query strings
- Cookies
- Content types
Express is a thin layer over the same objects. It adds:
- A router with path parameters
- The middleware pipeline with
next() - Helpers like
res.json(),res.status()andreq.params - Central error handling
app.listen still creates a plain http.Server underneath.
http.createServertakes a request listener function.reqis readable andresis writable, and you must callres.end().- With plain
node:http, routing and body parsing are manual. - Express adds routing, middleware, helpers and error handling.
- Express still runs on
http.Server.
Read more