node.js - Node.js + Express - 如何记录请求正文和响应正文
问题描述
我有一个使用 Node.js 和 express 构建的小 api。我正在尝试创建一个记录器,我需要记录请求正文和响应正文。
app.use((req, res) => {
console.log(req);
res.on("finish", () => {
console.log(res);
});
});
“快递”:“^4.16.3”,
但是,我无法在 req 或 res 对象中找到正文。请告诉我怎样才能得到它们。谢谢。
解决方案
res.body
尝试以下代码段:
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 });
推荐阅读
- python - 使用标准化 x 轴在同一 x 轴上绘制多条线
- c# - 同一根目录中的多个 C# 项目
- django - Django 从文件名中删除“@”和其他特殊字符
- google-my-business-api - 如何使用 GMB API 修补除摘要之外的 localPost?
- plotly - 将时间序列添加到袖扣 quantfig 图中
- javascript - 在 axios 发布后使用 React 钩子设置状态
- docker - 如何在 docker 容器中更改 freeradius-server 的配置?
- android - 字母“r”、“o”和“e”在 Android Studio 中无法正常工作?
- python - 遍历字典
- python - 将列中的所有值相乘 python pandas