Module 42: Web Servers with Express

Lesson 3 of 5 · 15–25 minutes

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

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
// src/routes/enquiries.ts
import { Router } from "express";
export const enquiriesRouter = Router();
enquiriesRouter.get("/", ...);
enquiriesRouter.get("/:id", ...);

// src/app.ts
app.use("/enquiries", enquiriesRouter);
app.use((req, res) => res.status(404).json({ error: "Not found" }));

🖱️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.

← PreviousExpress basics
ProLearners Assist