Reputation: 461
I want to log all requests like this:
8:04:20 PM - info: /api/v2 200
8:04:22 PM - info: /api/v2/asdf 200
However, in express, the middleware is called before the request is processed, so I cannot get the real response code. I always get 200. What is the right approach to accomplish this?
Upvotes: 7
Views: 16056
Reputation: 1279
As Edwin said, you could do the same without modifying your code using DEBUG environment variable, like this :
DEBUG=express:* && node server.js
Upvotes: 1
Reputation: 4052
Here you go:
app.use((req, res, next)=> {
console.log('I run on every request!');
next();
})
Upvotes: 7
Reputation: 461
You can use morgan to log your requests:
const morgan = require("morgan");
app.use(morgan('dev'));
For more documentation visit morgan. Yo may also be interested in on-finished package to execute arbitrary code on request completion.
Upvotes: 9
Reputation: 1450
Have your middleware below your routes and in your routes add a third parameter on the callback like this:
app.get( "/", function( req, res, next ) {
res.send(something);
next();
});
app.use(function(req, res, next) {
console.log('after request is done');
});
Upvotes: 0