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

后端 未结 3 2024
耶瑟儿~
耶瑟儿~ 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 });
    

提交回复
热议问题