Module 42: Web Servers with Express
Routes
🏠The everyday picture
A post office's counters: one for parcels, one for money orders, one for passports. Each request goes to the right counter by what it is and what it's for.
📘What it really is
- A route is a method plus a path, with a handler:
app.get("/enquiries", listHandler); // list
app.get("/enquiries/:id", getHandler); // one
app.post("/enquiries", createHandler); // create
app.patch("/enquiries/:id", updateHandler); // change
app.delete("/enquiries/:id", deleteHandler); // remove
- Parameters in the path:
req.params.id. Query parameters:req.query.status. Body:req.body. - Routers group related routes into their own file:
// src/routes/enquiries.ts
import { Router } from "express";
export const enquiriesRouter = Router();
enquiriesRouter.get("/", ...);
enquiriesRouter.get("/:id", ...);
// src/app.ts
app.use("/enquiries", enquiriesRouter);
- Unknown paths should get a JSON 404, not Express's default HTML page:
app.use((req, res) => res.status(404).json({ error: "Not found" }));
- Everything in
params,queryandbodycomes from outside: untrusted until checked (Module 43).
🖱️Try it
Create routes/enquiries.ts with all five routes using your file store from Module 41. GET /enquiries/:id returns
404 with a JSON error if not found. POST gives the new enquiry an id, status "new" and createdAt, and returns it
with status 201. Add the JSON 404 for unknown paths. Test with curl or the REST Client extension in VS Code.
✅Quick check
Where do you find E101 in a request to /enquiries/E101, and new in /enquiries?status=new?
Show the answer
req.params.id and req.query.status.
What status should creating an enquiry return?
Show the answer
201 Created, with the new enquiry in the body.
