【问题标题】:How can I console.log the res.body in Express nodejs如何在 Express nodejs 中控制台记录 res.body
【发布时间】:2019-01-27 21:40:28
【问题描述】:

我正在使用“express”:“^4.16.2”和“morgan”:“^1.9.1”, 但我无法记录响应正文。 在构建 res 后,我通过 console.log 对 res.body 进行了故障排除。它可以显示整个 res,但如果只记录 res.body,它会显示 undefined。

  app.use(express.json());   //build-in
  app.use(express.urlencoded({extended: true}));   
  app.use(morgan(loggerFormat, { stream: accessLogStream }));
......
//*****  Cannot get response body  */
// morgan.token('id', (req) => { return req.id; });
// morgan.token('reqBody', req => { return JSON.stringify(req.body) });
// morgan.token('resBody', (req, res) => {return JSON.stringify(res.body)});
// var loggerFormat = ':date[iso] :id :method :url \n :reqBody \n :status \n :resBody';
// app.use(morgan(loggerFormat, { stream: accessLogStream }));  // 3rd party

  app.post('/api/courses', (req, res) => {
  const { error } = validateCourse(req.body);
  if(error) return res.status(400).json({"error": error.details[0].message});

  const course = {
     id: parseInt(courses[courses.length-1].id) + 1,
     name: req.body.name,
     tutor: req.body.tutor
  };

  courses.push(course);
  res.status(200).json(course);
  console.log(res); 
  console.log(res.body);
});

我尝试提供的解决方案 Node.js + Express - How to log the request body and response body,但没用。

【问题讨论】:

  • 为什么不配置 Morgan 来记录正文?
  • console.log(res.body ) 在这里不起作用,因为这个 man res.status(200).json(course) 结束了请求,所以如果你想在控制台中看到 req.body将语句移到 res.status(200).json(course) 上方
  • 我将 Morgan 注释掉,因为它无法记录 res 正文。我尝试通过使用 console.log 找出问题所在
  • 以下链接可能会有所帮助,似乎同样的问题express-logging-response-body

标签: node.js


【解决方案1】:

试试这个

   console.log(res); 
   console.log(res.body)
  courses.push(course);
  res.status(200).json(course);

console.log 在发送响应之前记录 req.body

【讨论】:

  • 好的尝试使用正文解析器模块
猜你喜欢
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多