我有一个使用Node.js和express构建的小api。我正在尝试创建一个记录器,我需要记录请求体和响应体。
app.use((req, res) => {
console.log(req);
res.on("finish", () => {
console.log(res);
});
});
“表示”:"^4.16.3",
但是,我无法在req或res对象中找到身体。请告诉我怎么弄到它们。谢谢。
发布于 2018-09-13 01:53:11
您需要在请求中为您创建body对象的体解析器。
去做那个npm install body-parser
var bodyParser = require('body-parser')//add this
app.use(bodyParser())//add this before any route or before using req.body
app.use((req, res) => {
console.log(req.body); // this is what you want
res.on("finish", () => {
console.log(res);
});
});
发布于 2018-09-13 02:49:19
对于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 });
发布于 2021-08-06 14:08:57
遇到了这个问题,但不喜欢解决办法。一个简单的方法是简单地将原始的res.send或res.json与您的记录器打包。
将其作为中间件放在您的路由之前。
app.use(function responseLogger(req, res, next) {
const originalSendFunc = res.send.bind(res);
res.send = function(body) {
console.log(body); // do whatever here
return originalSendFunc(body);
};
next();
});
https://github.com/expressjs/express/blob/master/lib/response.js
res.send具有函数(主体)的签名{返回此;}
https://stackoverflow.com/questions/52310461
复制