In my small node.js application, using express, I wanted to log all the incoming requests, so I ended up with this:
var bodyParser = require('body-parser');
module.exports = function(app) {
app.set("port", 50001);
app.set("json spaces", 2);
app.use(bodyParser.json());
app.use(function (error, req, res, next) {
app.logger.info("received from "+req.get("X-Forwarded-For")+" : "+req.method+" "+req.originalUrl+" (Authorization: "+req.get("Authorization")+")");
//does not work if json is malformed
//app.logger.info("content :"+JSON.stringify(req.body));
if (error /*instanceof SyntaxError*/) {
res.status(400);
app.logger.error(error);
res.json({ error:{msg: error.message}});
} else {
next();
}
});
app.use(app.auth.initialize());
};
Unfortunately, I only get the logs via the app.logger.info
line when there's an error (in my case a malformed JSON string in the body). What am I missing here?
Expressjs adapts its functionality based on what type of callback you give it (this is not common in JS libraries so it is not surprising that people get confused by it).
If you do this where your callback has four arguments:
app.use(function(error, req, res, next) {...});
then Express assumes this is an error-only middleware handler and will only be called when there are errors. In the express doc, see the section labeled Error-handling middleware. Note this specific part of that page:
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):
And, here's a whole section of the documentation devoted to error handling middleware.
If you use just three arguments:
app.use(function(req, res, next) {...});
then, it is a normal middleware that is called when there are not errors. I'm not sure if they provide a single way to get both. But, certainly as a workaround, you could put your logging code into a function and then call that function from two separate middleware handlers, one for errors and one for non-errors.