Search code examples
javascriptnode.jshttpnpm-request

How can I get the raw HTTP message body using the request library in Node.js?


The npm request library allows me to construct HTTP requests using a nice JSON-style syntax, like this.

request.post(
    {
        url: 'https://my.own.service/api/route',
        formData: {
            firstName: 'John',
            lastName: 'Smith'
        }
    },
    (err, response, body) => {
        console.log(body)
    }
);

But for troubleshooting, I really need to see the HTTP message body of the request as it would appear on the wire. Ideally I'm looking for a raw bytes representation with a Node.js Buffer object. It seems easy to get this for the response, but not the request. I'm particularly interested in multipart/form-data.

I've looked through the documentation and GitHub issues and can't figure it out.


Solution

  • I figured out how to dump the HTTP message body with Request. In both cases, I'm just copying the same approach that request uses internally.

    Multipart Form Uploads

    req._form.pipe(process.stdout);
    

    URL-encoded Forms

    console.log(req.body);