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.