CodePark/ questions / HTTP servers & Express middleware
START PRACTICINGPRACTICE
Backend question · Node.js › HTTP servers & Express middleware

How do you create an HTTP server with the built-in node:http module, and what does Express add on top?

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() and req.params
  • Central error handling

app.listen still creates a plain http.Server underneath.

  • http.createServer takes a request listener function.
  • req is readable and res is writable, and you must call res.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.