Node.js + Express-如何记录请求正文和响应正文

时间:2018-09-13 09:15:37

标签: node.js express

我有一个使用Node.js构建并表达的小型api。 我正在尝试创建一个记录器,我需要记录请求正文和响应正文。

app.use((req, res) => {

    console.log(req);            

    res.on("finish", () => {

        console.log(res);

    });

});
  

“表达”:“ ^ 4.16.3”,

但是,我无法在req或res对象中找到该主体。请告诉我我怎么能得到它们。谢谢。

6 个答案:

答案 0 :(得分:4)

您需要body-parser才能在您的请求中为您创建主体对象。
为此 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);

  });

});

答案 1 :(得分:4)

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

答案 2 :(得分:1)

这是一个使用内置 PassThrough 流的工作示例。请记住使用 express.json() 内置中间件来启用请求正文解析。

之后,您需要拦截对响应流的所有写入。调用 writeend 时会发生写入,因此请替换这些函数并在单独的流中捕获参数。

使用 res.on('finish', ...) 将所有写入的数据收集到使用 Buffer.concat 的缓冲区中并打印出来。

const express = require('express');
const { PassThrough } = require('stream')

const app = express();

app.use(express.json());

app.use((req, res, next) => {
    const defaultWrite = res.write.bind(res);
    const defaultEnd = res.end.bind(res);
    const ps = new PassThrough();
    const chunks = [];

    ps.on('data', data => chunks.push(data));

    res.write = (...args) => {
        ps.write(...args);
        defaultWrite(...args);
    }

    res.end = (...args) => {
        ps.end(...args);
        defaultEnd(...args);
    }

    res.on('finish', () => {
        console.log("req.body", req.body);
        console.log("res.body", Buffer.concat(chunks).toString());
    })

    next();
})

app.use('/', (req, res) => {
    res.send("Hello");
});

app.listen(3000);

答案 3 :(得分:0)

安装npm install body-parser

并使用此代码段

var express = require('express')
var bodyParser = require('body-parser')
 
var app = express()
 
// create application/json parser
var jsonParser = bodyParser.json()
 
to get json response
app.use(jsonParser, function (req, res) {
  console.log(req.body); // or console.log(res.body);
})

答案 4 :(得分:0)

有现成的模块https://www.npmjs.com/package/morgan-body

const express = require('express')
const morganBody = require("morgan-body")
const bodyParser = require("body-parser")

const app = express()
const port = 8888

// must parse body before morganBody as body will be logged
app.use(bodyParser.json());

// hook morganBody to express app
morganBody(app, {logAllReqHeader:true, maxBodyLength:5000});

app.get('/', (req, res) => {
  res.send('Hello World!')

})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

答案 5 :(得分:0)

遇到了这个问题,但不喜欢解决方案。一个简单的方法是简单地用你的记录器包装原始 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 有 function(body) 的签名 { return this; }

相关问题