Node's original purpose was web servers. You can build one with the core http module, but almost everyone uses Express — a tiny framework that makes routing and middleware clean. This chapter builds up from raw HTTP to Express.
The http module
import http from "http";const server = http.createServer((req, res) => {res.writeHead(200, { "Content-Type": "text/plain" });res.end("Hello Albero");});server.listen(3000, () => console.log("http://localhost:3000"));
It works, but handling different URLs and methods by hand gets messy fast. That's what Express solves.
Express
npm install express
import express from "express";const app = express();app.get("/", (req, res) => {res.send("Hello Albero");});app.listen(3000, () => console.log("http://localhost:3000"));
Routing
A route maps an HTTP method + path to a handler. Handlers get req (the request) and res (the response). Read params, query strings and the JSON body:
app.get("/students/:id", (req, res) => {res.json({ id: req.params.id }); // /students/42 → { id: "42" }});app.get("/search", (req, res) => {res.json({ q: req.query.q }); // /search?q=data → { q: "data" }});app.post("/students", (req, res) => {res.status(201).json(req.body); // needs express.json() (below)});
Middleware
Middleware is a function that runs on the way in to your handlers — parsing bodies, logging, checking auth. Register it with app.use; call next() to continue:
app.use(express.json()); // parse JSON bodies into req.body// A custom loggerapp.use((req, res, next) => {console.log(req.method, req.url);next(); // pass control to the next middleware/route});
Practice
Build an Express app with a logger middleware, a GET / that returns a welcome message, and a GET /programmes/:id that echoes the id as JSON. Test it in the browser and with a tool like curl.
Key takeaways
- 01The http core module can serve requests, but routing by hand gets messy.
- 02Express maps method + path to handlers with req/res — install with npm install express.
- 03Read input from req.params (URL), req.query (query string) and req.body (JSON).
- 04Middleware runs before handlers (parsing, logging, auth); call next() to continue.
- 05Register express.json() before routes that read the body — order matters.
