Node.Js/Express-简单的中间件,用于输出响应的前几个字符 [英] Node.Js/ Express - simple middleware to output first few characters of response

查看:106
本文介绍了Node.Js/Express-简单的中间件,用于输出响应的前几个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于日志记录/调试,我想在响应发送到浏览器之前输出响应的前100个字符左右.我可以使用中间件和响应对象来完成一些简单的事情吗?

For logging/debugging I'd like to output the first hundred characters or so of the response right before its sent to browser. Is there something simple I can do with middleware and the response object to do this?

理想情况是:

app.use(function(req, res, next) {
    console.log('Response snippet: '+((res.body || '').substr(0,100)));
    next();
});

除了响应没有正文,我无法弄清楚当前要发送回的正文在哪里传递.

Except the response doesn't have a body and I cannot quite figure out where the current body to be sent back is passed.

更新:

Peter的答案行得通,我想我将中间件代码放在这里,以节省将来的观看者的点击次数:

Peter's answer worked, I figure I'd put my middleware code here to save future viewers a click:

App.use(function(req, res, next) {
    var end = res.end;
    res.end = function(chunk, encoding){
        res.end = end;
        if (chunk) {
            console.log(chunk);
        }
        res.end(chunk, encoding);
    };
    next();
});

推荐答案

因此,您需要挂钩到响应输出API,在中间件中,它不像挂钩到请求处理那样简单.最好的例子是 connect的内置函数记录器中间件.它基本上是猴子修补req.end方法并将该数据转发到其流,然后继续调用真正的req.end函数.您需要遵循这种模式,这种模式在非流式响应中应该可以正常工作.

So you need to hook into the response output API, which is not as straightforward in middleware as hooking into the request processing. The best example to look at is connect's built-in logger middleware. It basically monkey-patches the req.end method and forwards that data on to its stream, then proceeds to invoke the real req.end function. You need to follow this pattern, which should work fine for non-streaming responses.

该模式可能最终只会给您最后一块数据(对于流式响应的情况).如果是这样,您只需要猴子补丁res.write而不是res.end,就可以访问第一个块.记录完第一个块后,只需取消猴子补丁res.write.

That pattern may end up only giving you the last chunk of data (for the case of a streamed response). If so, you need to just monkey-patch res.write instead of res.end and you'll get access to the first chunk. Just un-monkey-patch res.write once you've logged the first chunk.

这篇关于Node.Js/Express-简单的中间件,用于输出响应的前几个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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