Reputation: 549
In my small chat application, when I make a HTTP call to an endpoint ending in "users" I want my room router to take over. This be with a preceding room name, or with nothing at all.
routes.js:
module.exports = function(app) {
var roomRoute = require('./routes/room');
app.use('/:roomname/users', roomRoute);
app.use('/users', roomRoute);
};
Now when my room router takes over, I want to be able to access the room name if it exists in the url. Something like:
./routes/room.js:
var express = require('express');
var router = express.Router();
router.get('/info', function(req, res) {
console.log('the roomname is ' + req.roomname);
res.end();
});
module.exports = router;
Is there any way to easily pass this room name along? I could probably extract it from the baseUrl but I think there is probably a better way...
Upvotes: 2
Views: 1603
Reputation: 824
The router needs to set the mergeParams
option to true.
http://expressjs.com/en/4x/api.html#express.router
let router = express.Router({ mergeParams: true });
Upvotes: 4
Reputation: 549
The very next thing I read after I posted had the answer...
In routes.js:
var roomRoute = require('./routes/room');
app.use('/:roomname/users', function (req, res, next) {
req.roomname = req.params.roomname;
next();
}, roomRoute);
app.use('/users', roomRoute);
Upvotes: 2