简体   繁体   中英

Log requests to nodejs express

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?

Here you go:

app.use((req, res, next)=> {
  console.log('I run on every request!');
  next();
})

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.

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM