I already use the middleware facility in Express.js by means of app.use()
to hook on all requests and log a message, but found the fact that res.statusCode
is nearly always 200, which I checked is not correct. I presume this is the default value and since it is not yet replaced with my own statusCode
with res.send(204)
well, is always 200.
I know I can log the message after every res.send(x)
in every request, but as you might imagine, that is cumbersome.
So, the question is:
Where/How can I hook my middleware function with the conditions that is only in one place and res.statusCode
is the one that the client really sees?
Relevant code:
// Log API requests.
app.use(function (req, res, next) {
logger.info('API request.', {
module: 'core'
data : {
req: {
method: req.method,
url : req.url,
ip : req.ip
},
res: {
status_code: res.statusCode // Always 200 and not the really one.
}
}
});
next();
});
app.use(app.router);
If I move app.use(app.router)
the middleware don't get executed.