标题应该很自我解释。
为了进行调试,我希望表达能够为每个服务请求打印响应代码和正文。打印响应代码很简单,但打印响应体很复杂,因为响应体似乎不能作为属性使用。
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);更多推荐
快速记录响应体
发布评论