本文介绍了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);
});
});
但是,我无法在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 });
这篇关于Node.js + Express-如何记录请求正文和响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!