-2

I want to send the following request to some external API:

curl "https://api.foo.com/v2/" \
  -u USERNAME_OR_ACCESS_TOKEN \
  -X POST \
  -F file=@/path/to/my/file.json

But I want to do this with node. The file parameter is supposed to be a file - how can I do this from the node level? How can I send the file like here in cURL?

I've been trying to provide a string to the file relative to the node binary location, but of course it doesn't work:

this.api.sendRequest("https://api.foo.com/v2/", "POST", {
  file: "path/to/my/file.json"
});
user99999
  • 1,994
  • 5
  • 24
  • 45
  • Possible duplicate of [Uploading file using POST request in Node.js](http://stackoverflow.com/questions/25344879/uploading-file-using-post-request-in-node-js) – shaochuancs May 17 '17 at 03:09
  • If you are looking for native Node.js solution without any third-party module, please check http://stackoverflow.com/questions/37712081/uploading-a-file-with-node-http-module – shaochuancs May 17 '17 at 03:10

1 Answers1

0

You may want to take a look at the npm request package. An example of sending a file is below:

const request = require('request');
const fs = require('fs');

request.post({
   url: "https://api.foo.com/v2/",
   formData: { file: fs.createReadStream("path/to/my/file.json") }
});

request.post() will return a promise which you can .then() and pass success and error callbacks to.

Read more about request forms here: https://www.npmjs.com/package/request#forms

kennasoft
  • 1,595
  • 1
  • 14
  • 26