Module 42: Web Servers with Express
Express basics
🏠The everyday picture
A ready-built counter with labelled trays, a stamp and a cash box, instead of building the counter yourself from planks.
📘What it really is
- Express is the most widely used Node.js web framework: small, flexible and well documented.
// src/app.ts
import express from "express";
export const app = express();
app.use(express.json());
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
// src/server.ts
import { app } from "./app.ts";
import { config } from "./config.ts";
app.listen(config.port, () => {
console.log(`API listening on http://localhost:${config.port}`);
});
express.json()reads JSON request bodies intoreq.body.res.json(value)sends JSON with the right content type;res.status(201).json(...)sets a status first.-
Keeping
app(the routes) separate fromserver(listening on a port) lets tests use the app without starting a real server (Module 46). -
Similar frameworks: Fastify (faster, built-in validation), Hono (tiny, runs in many places), NestJS (large, structured). The ideas are the same.
🖱️Try it
Set up app.ts and server.ts as above. Run npm run dev and visit /health. Add a GET / route that returns the
API's name and version.
✅Quick check
What does app.use(express.json()) do?
Show the answer
It reads JSON request bodies so they're available as req.body.
Why separate app.ts from server.ts?
Show the answer
Tests can use the app's routes directly without starting a server on a port.
