In this lesson, you followed a URL from the café’s app into the tickets router, and then into a notes router mounted inside it, to see which part of the URL each router matches.
Key Points
- Express takes the mount path off before the router matches. For
GET /tickets/1, the app’suseentry for/ticketsmatches the URL’s first segment,/tickets, as a whole segment. Express keeps that part inreq.baseUrland hands the router the rest inreq.url, which is/1. The list route"/"doesn’t match it, and the ID route"/:id"does, withreq.params.idset to"1". - A route’s full URL is its mount path, then the router’s own path. That’s why the router’s paths leave the mount path out. Written as
"/tickets/:id"inside the router, the ID route answers at/tickets/tickets/1, and/tickets/1gets Express’s404page,Cannot GET /tickets/1. - A router can mount another router, and a mount path can hold a route parameter. The line
ticketsRouter.use("/:id/notes", notesRouter);sends/tickets/1/noteson to the notes router. The app strips/tickets, and the tickets router gets/1/notes. Neither of its routes matches two segments, so the request reaches the new mount, which strips/1/notesand adds it toreq.baseUrl. The notes router gets/, and its route matches. - A router starts with only the params from its own paths. The
idwas matched by the tickets router’s mount path, so theidparam belongs to the tickets router. The notes router still sees/1in itsreq.baseUrl, but not as a param, so itsreq.paramswas an empty object. mergeParams: truepasses the parent’s params down. Created withexpress.Router({ mergeParams: true }), the notes router’sreq.paramsholds the ticket’s ID, the string"1", so it can tell which ticket the notes are for.
To predict a route’s full URL, add up the mount paths on the way down, then the route’s own path: /tickets + /:id/notes + / is /tickets/:id/notes. Each router strips its part before the next one matches, and a child router sees its parent’s params only when mergeParams is on.