Reputation: 108
I'm trying to initialize multiple express router params using the router.param method. Here's a router code snippet:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
router.param(['foo','bar'], function(req,res,next,foo,bar){
req.myvars = {
foo: foo,
bar: bar
};
console.log('initialized params: foo==%s, bar==%s', foo, bar);
return next();
});
router.get('/myvars/:foo/:bar',function(req,res,next){
var foo = req.myvars.foo;
var bar = req.myvars.bar;
console.log('router.get: foo==%s, bar==%s', foo, bar);
res.json(req.myvars);
});
module.exports = router;
I'm getting an error when browsing to http://localhost:3000/myvars/a/b: Cannot read property 'foo' of undefined. Also, my console window does not show the 'initialized params' like I expected. Is router.param not getting invoked? How do I use the router.param method properly? I see many examples online (eg. API example of using router.param with only a single name: could someone give a code example of using router.param with an array of names?
If necessary, here's my package.json dependencies.
"dependencies": {
"express": "~4.8.6",
"body-parser": "~1.6.6",
"cookie-parser": "~1.3.2",
"morgan": "~1.2.3",
"serve-favicon": "~2.0.1",
"debug": "~1.0.4",
"jade": "~1.5.0"
}
Upvotes: 1
Views: 644
Reputation: 21
Well it does support arrays, but you can't resolve both params at the same time. If you look at the docs again.
router.param(['id', 'page'], function (req, res, next, value) {
console.log('CALLED ONLY ONCE with', value);
next();
})
You have to access their values in a for each style. Also I don't know why you would return a next()
. I don't think it will cause any problems, but just call next()
and let function terminate on its own.
Upvotes: 0
Reputation: 203534
Looking at the Express router code, it doesn't actually accept an array of names (even though the documentation suggests it does).
You can work around it with something like this:
var handler = function(req, res, next, value, key) {
req.myvars = req.myvars || {};
req.myvars[key] = value;
next();
};
router.param('foo', handler);
router.param('bar', handler);
Upvotes: 2