简体   繁体   中英

How do I send a file with node.js request module?

I am trying to use an API to update a list on another server using node.js. For my last step, I need to send a POST that contains a csv file. In the API, they list under FormData that I need a Key called file and a Value of Binary Upload, then the body of the request should be made of listname: name and file: FileUpload.

function addList(token, path, callback) {

//Define FormData and fs
var FormData = require('form-data');
var fs = require('fs');

//Define request headers.
headers = {
    'X-Gatekeeper-SessionToken': token,
    'Accept': 'application/json',
    'Content-Type': 'multipart/form-data'
};

//Build request.
options = {
    method: 'POST',
    uri: '{URL given by API}',
    json: true,
    headers: headers
};

//Make http request.
req(
    options,
    function (error, response, body) {
        //Error handling.
        if (error) { callback(new Error('Something bad happened')); }

        json = JSON.parse(JSON.stringify(response));
        callback.call(json);
    }
);

//Attempt to create form and send through request
var form = new FormData();
form.append('listname', 'TEST LIST');
form.append('file', fs.createReadStream(path, { encoding: 'binary' }));
form.pipe(req);};

I am a veteran of front end javascript for html and css, but this is my first adventure with backend node.js. The error I keep getting is: TypeError: dest.on is not a function

From what I can tell, this has to do with the way I used form.pipe(req) but I can't find documentation telling me the appropriate usage. If you don't have a direct answer, a finger pointing toward the right documentation would be appreciated.

The issue is you're not passing the request instance into your pipe call, you're passing the request module itself. Take a reference to the return value of your req(...) call and pass this instead ie

//Make http request.
const reqInst = req(
   options,
   function (error, response, body) {
       //Error handling.
       if (error) { callback(new Error('Something bad happened')); }

       json = JSON.parse(JSON.stringify(response));
       callback.call(json);
   }
);

//Attempt to create form and send through request
var form = new FormData();
...
form.pipe(reqInst);

This line:

.pipe(fileinclude)

Should be this:

.pipe(fileinclude())

from

why am i getting this error? dest.on is not a function - using gulp-file-include

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM