快速记录响应体

编程入门 行业动态 更新时间:2024-10-27 21:15:48
本文介绍了快速记录响应体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

标题应该很自我解释。

为了进行调试,我希望表达能够为每个服务请求打印响应代码和正文。打印响应代码很简单,但打印响应体很复杂,因为响应体似乎不能作为属性使用。

For debugging purposes, I would like express to print the response code and body for every request serviced. Printing the response code is easy enough, but printing the response body is trickier, since it seems the response body is not readily available as a property.

以下内容不起作用:

var express = require('express'); var app = express(); // define custom logging format express.logger.format('detailed', function (token, req, res) { return req.method + ': ' + req.path + ' -> ' + res.statusCode + ': ' + res.body + '\n'; }); // register logging middleware and use custom logging format app.use(express.logger('detailed')); // setup routes app.get(..... omitted ...); // start server app.listen(8080);

当然,我可以轻松地在发出请求的客户端打印响应,但是我宁愿在服务器端也做。

Of course, I could easily print the responses at the client who emitted the request, but I would prefer doing at the server side too.

PS:如果它有帮助,我的所有回复都是json,但希望有一个解决方案适用于一般响应。

PS: If it helps, all my responses are json, but hopefully there is a solution that works with general responses.

推荐答案

不确定是否是最简单的解决方案,但您可以编写一个中间件来拦截写入响应的数据。确保您禁用 apppress()。

Not sure if it's the simplest solution, but you can write a middleware to intercept data written to the response. Make sure you disable apppress().

function logResponseBody(req, res, next) { var oldWrite = res.write, oldEnd = res.end; var chunks = []; res.write = function (chunk) { chunks.push(chunk); oldWrite.apply(res, arguments); }; res.end = function (chunk) { if (chunk) chunks.push(chunk); var body = Buffer.concat(chunks).toString('utf8'); console.log(req.path, body); oldEnd.apply(res, arguments); }; next(); } app.use(logResponseBody);

更多推荐

快速记录响应体

本文发布于:2023-11-26 04:38:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!