在expressjs的中间件中获取res.send值 [英] Get the res.send value in middleware for expressjs

查看:121
本文介绍了在expressjs的中间件中获取res.send值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一些中间件,该中间件将记录所有路由的请求主体和响应主体.记录请求很简单,但是,我似乎无法获得响应. res.on('end')不会发出任何数据,我看不到任何与Express相关的东西会发出或应用此数据.会有人对如何实现这一目标有什么建议吗?

I'd like to create some middleware that would log the request body and response body of all routes. Logging the request is straight forward, however, I can't seem to get the response. res.on('end') doesn't emit any data and I'm not seeing anything specifically tied into express that would emit or apply this. Would anyone have any suggestions how to achieve this?

根据kook答案中的链接,我想出了这个方法,它似乎运行良好.

Based on the links in kook's answer, I've come up with this, which seems to work well.

app.use(function(req, res, next) {
    var send = res.send;
    res.send = function(body){
      console.log(body);
      res.send = send;
      res.send(body);
    };
    next();
});

推荐答案

您是否看到过类似的帖子?我认为您应该能够遵循他们的逻辑来创建自己的逻辑:

Have you seen these posts about similar? I think you should be able to follow their logic in creating your own:

表达日志记录响应正文

Node.Js/Express-简单的中间件,用于输出响应的前几个字符

这篇关于在expressjs的中间件中获取res.send值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆