Shanir
Shanir

Reputation: 87

NodeJS: forward form-data to external API

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:

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

Upvotes: 2

Views: 2021

Answers (1)

davidrv87
davidrv87

Reputation: 908

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

Upvotes: 1

Related Questions