I'd like to isolate a piece of code that would inspect either req.params
or req.body
for a value that is required on every request. What I'm finding is that if I try to access those values before app.use(app.router)
then the request hasn't been parsed to include those objects. If I try to insert the middleware after app.use(app.router)
then it gets skipped all together.
What can I do to work on these values in one place so that the work is ready to be used by downstream routes and models?
Since my original answer won't obtain route parameters from the URL, e.g. /things/:foo
(although it will get querystring and req.body params), it won't work the way we want. But another option would be to write a wrapper function that does what you need, and apply it to your route middleware:
function checkForParam (fn) {
return function(req, res, next) {
if (req.param('foo') != 'bar') {
return res.send(403, 'No way Jose!');
}
fn (req, res, next);
};
}
Then add routes with:
app.get('/things/:foo', checkForParam(function(req, res, next) {
// your middleware code here
});
This will run the check and proceed to your custom route middleware only if it passes muster.
Rather than attempting to do this via custom middleware, you could simply add a wildcard route that will always run before your other routes, and check for the param in there:
app.get('/*', function(req, res, next) {
if (req.param('foo')) {
// Do something
return next(); // or return res.send(403, 'no way!'), or whatever.
}
return next();
});
There is one question left : Are you using Express v. 3 or 4 ???
This is very important here because the concept in v. 4 is different (aka better).
e.g. https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.x
app.use(app.router); // <--- this line will be removed