Named Route Parameters
The :thingId Lane
Section titled “The :thingId Lane”Sometimes we don’t just want any thing, we want a specific thing. Route parameters are named URL segments that are used to capture the values specified at their position in the URL. We flag them with a colon (:).
Fig 1: The Designated Lane.
This allows us to create dynamic routes. Instead of hardcoding /users/1, /users/2, /users/3, we create one lane that handles them all.
// Route path: /things/:thingId// Request URL: http://localhost:3000/things/42app.get('/things/:thingId', (req, res) => { // Access the param via req.params console.log(req.params); // { thingId: '42' }
res.send(`Details for thing #${req.params.thingId}`);});The captured values are populated in the req.params object. It’s like an designated lane pass — it lets specific traffic through based on ID.
Multiple Parameters
Section titled “Multiple Parameters”We can have multiple segments in a single route.
// Route path: /flights/:from/:to// Request URL: http://localhost:3000/flights/YVR/LAXapp.get('/flights/:from/:to', (req, res) => { const { from, to } = req.params; res.send(`Flying from ${from} to ${to}`);});Professor Solo’s Directive: Parameter names are case-sensitive and must be made up of word characters ([A-Za-z0-9_]). Don’t get cute with emojis in variable names.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Named Route Parameters - Demo Repo
Express Route Parameters