1

I am trying to upload a file in a https request using form data. I have this

function uploadDocument(filepath) {
    var options = {
        host : 'myserver',
        port : 443,
        path : '/platform-api/v1/documents',
        method : 'POST',
        headers : {
            'Authorization' : 'Bearer 56356363',
            'Accept' : 'application/json'
        }
    };
    var req = https.request(options, function(res) {
        var buffer = "";
        res.on('data', function(chunk) {
            buffer += chunk;
        });
        res.on('end', function(chunk) {
            var json = JSON.parse(buffer.toString());
            console.log(json);
        });
    });

    var form = new FormData();
    form.append('file', fs.createReadStream(filepath));
    form.append('project_id', 4);
    form.pipe(req);

    req.on('error', function(e) {
        console.log('problem with request:', e.message);
    });
    req.end();
}

but I get back

problem with request: write after end
{ errors:
   { file: 'missing-required-key',
     project_id: 'missing-required-key' } }

Does anyone know what is wrong?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474
  • Possible duplicate: https://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request-in-node-js – Baruch Sep 28 '17 at 22:42
  • How can I wait for the pipe to finish like asked here https://stackoverflow.com/questions/46479347/how-to-wait-for-the-pipe-to-finish-in-form-data-node-js-module – omega Sep 28 '17 at 22:47
  • try removing `req.end()` the documentation seems to be saying that it works without it – forJ Sep 29 '17 at 00:13

1 Answers1

0

Just don't use req.end() when pipe already called.

FormData is asynchronous stream and you can't call req.end() right after calling .pipe(req). According to docs, pipe by default calls end() for the writer stream (req in this case) when reader stream (form itself) ends.

So use req.end() when you don't need pipe, and don't use req.end() if you used pipe.