首页 > 解决方案 > 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 对象中找到正文。请告诉我怎样才能得到它们。谢谢。

标签: node.jsexpress

解决方案


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 });

推荐阅读