2

Looking for help to solve my issue, any advice appreciated!

So I'm uploading csv file as formdata to Node environment with XHR request:

       var FormData = new FormData();
    var file = input.files[0];
FormData .append("file", file);

In the Node environment I receive the following under req.files with JSON.stringify: req.files

Next I need to add authorization header and send the same data to external API.

What I have tried:

  • using request module and ```.pipe()``
  • using busboy
  • and axios with form-data
  • basically all these posts: 1, 2, 3, 4, 5, 6, 7

But file is not being sent correctly and server responds with 400.

Limitations As this Node environment is cloud based I cannot access any of the config js files and therefore use express.

Thanks

Shanir
  • 87
  • 6
  • It would be helpful to include the code of your attempts, e.g. with the `request`-module. Also are you able to perform the upload to the remote server using curl/postman? – eol Jun 18 '20 at 09:30
  • @eol I though of adding code, but it would create hell of a long post, as I tried 10-15 different ways. I didn't use `fs createStream` as I do not have the path, though. But uploading file from postman works, also uploading directly from browser works, the problem is with forwarding only. – Shanir Jun 18 '20 at 10:16
  • @Shanir Any luck on this? I m also facing the same – Muthu Sep 11 '20 at 07:59

1 Answers1

1

You can achieve what you are looking for with axios

const axios = require("axios")
const FormData = require("form-data")
const fs = require("fs")

const url = "your.url.com"
const form_data = new FormData()
form_data.append("file", fs.createReadStream(localPath))

const request_config = {
  headers: {
    ...form_data.getHeaders()
  },
  maxContentLength: Infinity,
  maxBodyLength: Infinity,
  auth: { // if auth is needed
    username: USERNAME,
    password: PASSWORD
  }
}

return axios.post(url, form_data, request_config)

Hope it helps

davidrv87
  • 838
  • 7
  • 16
  • Thanks @davidrv87 The problem with using `fs.createReadStream` is that I don't understand what to pass for the path of the file? I do not see any path in the request.. – Shanir Jun 18 '20 at 10:20
  • There is no need to pass a file. You can pass values - see https://developer.mozilla.org/en-US/docs/Web/API/FormData/append – davidrv87 Jun 18 '20 at 14:04