Wednesday, 19 April 2017

Nodejs sending file through http and formData

I'm trying to send a file to another node.js service. So for that i'm using http and form-data modules.

This is the code i wrote

function (file) {     
    var crlf = "\r\n",
        boundaryKey = Math.random().toString(16),
         boundary = `--${boundaryKey}`;

    var formData = new FormData();
    formData.append('file', file);   


    var options = {
        host: 'localhost',
        port: 3005,
        method: 'POST',
        path: '/files',
        headers: {
            'Content-Type': 'multipart/form-data; boundary=' + boundary,
            'Content-Length': formData._valueLength
        }
    };

    //make request
    return httpsRequest(formData, options)
        .then((result) => {

           console.log(result);
        }, (err) => {

            console.log(err);

        });
};


function httpsRequest(data, options) {

    return new Promise(function (resolve, reject) {
        // request object
        var req = https.request(options, function (res) {
            var result = '';
            res.on('data', function (chunk) {
                result += chunk;
            });
            res.on('end', function () {
                console.log("https end result - " + result);
                resolve(result);
            });
            res.on('error', function (err) {
                reject(err);
            })
        });

        // req error
        req.on('error', function (err) {
            reject(err);
        });

        //send request witht the postData form
        req.write(data);
        req.end();

    });
}

It is giving "First argument must be a string or Buffer" this error. It looks like something is wrong on the httpsRequest function.



via kohli

No comments:

Post a Comment