我正在尝试编写一个小型 API 记录器作为 Express 中间件。记录器从 req 和 res 中收集各种信息,然后将 JSON 文件保存到磁盘以供以后读取。
这是我当前存储日志的功能。
function store(req, res, next) {
init();
const log = {
request_url: req.hostname,
request_body: req.body,
request_method: req.method,
request_headers: req.headers,
api_endpoint: req.baseUrl,
timestamp: moment().format('x')
};
res.on('finish', () => {
log.response_body = res.body;
log.response_status = res.statusCode;
global.enoch_logs.push(log);
fs.writeFile(`./logs/${ moment().format('x') }.json`, JSON.stringify(log), (err) => (err) ? console.log(err) : null);
});
next();
}
问题在于 res.body 始终为空。我尝试了几种不同的方法来捕获响应正文,但似乎没有任何效果。
我哪里出错了?
尝试导入主体解析器。 例如。从“body-parser”导入bodyParser;