Node.js + Express-如何记录请求正文和响应正文
问题描述:
我有一个使用Node.js构建并表达的小型api. 我正在尝试创建一个记录器,我需要记录请求正文和响应正文.
I have a small api I have built using Node.js and express. I am trying to create a logger and I need log the request body AND response body.
app.use((req, res) => {
console.log(req);
res.on("finish", () => {
console.log(res);
});
});
表达":"^ 4.16.3",
"express": "^4.16.3",
但是,我无法在req或res对象中找到该主体.请告诉我我怎么能得到它们.谢谢.
However, i am not able to find the body in the req or res object. Please tell me how i can get them. thanks.
答
对于res.body
,请尝试以下代码段:
For res.body
try the following snippet:
const endMiddleware = (req, res, next) => {
const defaultWrite = res.write;
const defaultEnd = res.end;
const chunks = [];
res.write = (...restArgs) => {
chunks.push(new Buffer(restArgs[0]));
defaultWrite.apply(res, restArgs);
};
res.end = (...restArgs) => {
if (restArgs[0]) {
chunks.push(new Buffer(restArgs[0]));
}
const body = Buffer.concat(chunks).toString('utf8');
console.log(body);
defaultEnd.apply(res, restArgs);
};
next();
};
app.use(endMiddleware)
// test
// HTTP GET /
res.status(200).send({ isAlive: true });