Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting request body from response object

I'm trying to retrieve the body of a request via the response object.

var request = require('request');

request({
    ...
    body: {
        foo: 'bar'
    }
}, function(err, res, body) {
    var reqBody = res.request.body;
});

But the request body is now a Buffer. How can I turn this back into a JavaScript object?

Note: I can't store the request body in a variable with larger scope before making the http request.

like image 264
Cody Avatar asked Jul 24 '14 19:07

Cody


1 Answers

Figured it out, way simpler than I thought.

var reqBody = res.request.body.toString();
reqBody = JSON.parse(reqBody);

First convert it to JSON, then convert the JSON to a JavaScript object.

like image 54
Cody Avatar answered Oct 14 '22 02:10

Cody