Search code examples
node.jsrequestmultipartform-dataform-data

Using request module and passing the body to the next request


I am using request to get an image:

request(req.body.imageUrl, {encoding: null}, function(error, response, body) {

I then want to use the body to pass to an api that uses a multipart form and send that image (which is now in the body). I don't want to write the file to disk and then readstream from the disk again. I basically want to enter the formData of the next request by using the Buffer of the body, but it is not working.

So, for the options in the next request I have:

const options = {
                method: "POST",
                url: coreURL,
                headers: {
                    "Content-Type": "multipart/form-data"
                },
                formData : {
                    file : new Buffer.from(body,'binary')
                }
            };

And this does not work, if I write the body to a file fs.writeFileSync(fileName, body, 'binary');

And then read in the options formData : { file : fs.createReadStream(fileName)}

it works but I cannot use the disk, so need an alternative way to pass the body into the next post as multipart form data.

Any ideas?


Solution

  • POC:

    let request = require('request');
    
    request.post({
            url: "http://httpbin.org/anything",
            formData: {
                myfile: request.get("https://www.gravatar.com/avatar/f056d36f9e273fd4740ec8a5cea1348a"),
            }
        },
        function (err, req, body) {
            console.log(body);
        }
    );