How do I pass a parameter to express.js Router?
Here's what I've come up with: I pass the "mini-app configuration" by assigning it to req
:
app.use('/birds', function (req, res, next) {
req.animal_config = {
name: 'Bird',
says: 'chirp'
};
next();
}, animal_router);
app.use('/cats', function (req, res, next) {
req.animal_config = {
name: 'Cat',
says: 'meow'
}
next();
}, animal_router);
and then in my route I can access them:
var express = require('express');
var router = express.Router();
...
router.get('/about', function(req, res) {
var animal = req.animal_config;
res.send(animal.name + ' says ' + animal.says);
});
This approach allows to easily mount the "mini-app" at another location providing different configuration, without modifying the code of the app:
app.use('/bears', function (req, res, next) {
req.animal_config = {
name: 'Bear',
says: 'rawr'
};
next();
}, animal_router);
You're basically talking about injecting configuration to a router.
I have faced with similar problem and figured out that in theory you can export not a router itself, but rather function that accepts configuration and returns created and configured router.
So in your case calling code will look like:
var animal_router = require('./animal_router')
app.use('/birds', animal_router({
name: 'Bird',
says: 'chirp'
}));
app.use('/cats', animal_router({
name: 'Cat',
says: 'meow'
}));
While ./animal_router.js
might look following:
var express = require('express');
// Create wrapper function that will adjust router based on provided configuration
var wrapper = function (animal_config) {
var router = express.Router();
router.get('/about', function(req, res) {
var animal = animal_config;
res.send(animal.name + ' says ' + animal.says);
});
return router;
}
module.exports = wrapper;
So, if you want to serve changes by url, then you can inject params like this:
router.get('/:animal/about', function(req, res) {
// here we have bird or fish in req.params.animal
if(req.params.animal == 'bird') {
res.send('Birds can fly');
} else if(req.params.animal == 'fish') {
res.send('Fish can swim');
} else {
res.send('Unknown animal');
}
});
app.use('/', router);