node.js - 有没有办法监控 Express.js 中的每个响应?

标签 node.js express

我想在express.js中创建一个中间件函数。它可以监控每个请求和响应。我创建了一个中间件,但它只能监视请求,不能监视响应。

function middlewareFunc (req,res,next) {
  console.log(req.body , req.params , req.query);
  next();
}

最佳答案

您应该知道 function(req, res, next) 中的 res 是类 http.ServerResponse 的实例。因此可以监听 finish 事件,请参阅链接:https://nodejs.org/api/stream.html#stream_event_finish

app.use(function (req, res, next) {
    function afterResponse() {
        res.removeListener('finish', afterRequest);
        res.removeListener('close', afterRequest);

        // action after response
    }

    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    // action before request
    // eventually calling `next()`
});

app.use(app.router);

app.use() 和中间件可用于“before”,并且可使用 closefinish 事件的组合表示“之后”。

关于node.js - 有没有办法监控 Express.js 中的每个响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716058/

相关文章:

node.js - Angular 9 SSR 404 未找到带有状态代码的页面

node.js - 防止在 Express JS 中从缓存获取 Json 响应

node.js - 同步使用 Alchemy API

node.js - 在文件夹中创建 Google Sheets 文档(无需移动和删除旧文档)

javascript - Express:如何在调用某些内容之前等待函数完成

javascript - 在 promise 中得到 Express 回复?

javascript - 在 node.js 代码中实现回调的问题

python - 如何保证服务器身份?

node.js - 如何将winston日志路径设置为项目本地文件夹

performance - 我将如何限制 node.js 中服务器的上传速度?