1

I am using "express": "^4.16.2" and "morgan": "^1.9.1", but I can't log the response body. I troubleshooted by console.log the res.body after building the res. It can show the whole res, but if just log the res.body, it shows 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);
});

I try the solution provided by Node.js + Express - How to log the request body and response body, but it doesn't help.

pazjing
  • 11
  • 1
  • 3
  • Why don't you configure Morgan to log the body? – jonrsharpe Jan 27 '19 at 21:48
  • console.log(res.body ) won't work here because this man res.status(200).json(course) ends the request so if u want to see req.body in your console move the statement above this res.status(200).json(course) – elraphty Jan 27 '19 at 21:51
  • I comment out the Morgan because it can't log the res body. And I try to figure out where it is wrong by using console.log – pazjing Jan 29 '19 at 09:32
  • Might following link could help, Seems same issue [express-logging-response-body](https://stackoverflow.com/questions/19215042/express-logging-response-body) – Devendra Chhaiya Aug 15 '20 at 05:32

1 Answers1

0

Try this

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

console.log the req.body before sending a response

elraphty
  • 630
  • 6
  • 13