Node.js + Express - How to log the request body and response body

后端 未结 3 1988
耶瑟儿~
耶瑟儿~ 2021-01-12 20:51

I have a small api I have built using Node.js and express. I am trying to create a logger and I need log the request body AND response body.

app.use((req, re         


        
相关标签:
3条回答
  • 2021-01-12 21:14

    For res.body try the following snippet:

    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 });
    
    0 讨论(0)
  • 2021-01-12 21:20

    You need body-parser that will create body object for you in your request.
    To do that 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);
    
      });
    
    });
    
    0 讨论(0)
  • 2021-01-12 21:26

    install npm install body-parser

    and use this snippet,

    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);
    })
    
    0 讨论(0)
提交回复
热议问题