简体   繁体   English

将请求记录到 nodejs express

[英]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.但是,在express中,中间件在处理请求之前被调用,所以我无法得到真正的响应代码。 I always get 200. What is the right approach to accomplish this?我总是得到 200。实现这一目标的正确方法是什么?

Here you go:给你:

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

You can use morgan to log your requests:您可以使用 morgan 来记录您的请求:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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