Router Base Paths
Merging Traffic Routers
Section titled “Merging Traffic Routers”We have our thingRouter.js, but app.js needs to know about it. We connect them using app.use(), and we give it a Base Path.
Fig 1: Taking the Exit.
app.js
Section titled “app.js”const thingRouter = require('./routes/thingRouter');
// Mount the router// Any request starting with "/things" goes hereapp.use('/things', thingRouter);Context Awareness
Section titled “Context Awareness”The magic here is that inside thingRouter.js, the router doesn’t know about the /things prefix. It only cares about what comes after.
Once you take the exit, you are no longer on the highway.
When we mount a router on /things, Express strips that part of the URL off before handing the request to the router.
- Request URL:
/things/42 - Main App sees:
/things-> passes control tothingRouter - Router sees:
/42
So inside thingRouter.js, we must REMOVE the prefix we added in the previous lesson:
// OLD (Wrong inside a mounted router)// router.get('/things', ...)
// NEW (Correct)// Matches /things/router.get('/', (req, res) => res.send('List of Things'));
// Matches /things/:idrouter.get('/:id', (req, res) => res.send('Details of Thing'));We’ve effectively removed the repetitive /things prefix from inside the router file.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Router with Base Paths - Demo Repo
Express Guide: Router