Getting request body from response object

12,718

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.

Share:
12,718
Cody
Author by

Cody

Updated on June 20, 2022

Comments

  • Cody
    Cody about 2 years

    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.

  • Dee
    Dee almost 7 years
    that 'toString' on body doesn't work, i have to use JSON.stringify