2

I need to save request a response body in my NodeJS API. I use express. express get response body

I write tow middleware. first: process the client request.

app.use((req, res,next) => {

res.status(404).json({
    errors: [{
            field: "url",
            message: "not found"
        }]
});

next();

});

second: log or save the request and response body.

app.use((req, res,next) => {

console.log(req.body);
console.log(res); //here I want get response body

});

my question is how can I access to the response body in express? if there isn't any way how can I save request and response body in NodeJS?

1 Answers1

3

You should bind a callback for finish event of response

app.use((req, res,next) => {
    console.log(req.body);
    res.on('finish', () => console.log(res)); //get response body in callback
});

because the response object is not fully available when the middleware is executed.

ylc395
  • 93
  • 1
  • 5