12

I'm getting this error when trying to do a POST request using axios:

TypeError: data should be a string, Buffer or Uint8Array

Here is my code snippet:

var fs = require('fs'),
axios = require('axios');

var FormData = require('form-data');
var form = new FormData();
form.append('file', fs.createReadStream("qa_test_file_DOC.txlf"));
form.append('extractArchive', false);


let request_config = {
    headers: {
    'Authorization': `Bearer eyJhbGciOiJIUzI1NXXXX.....`,
    ...form.getHeaders()
 }
}

let reqUrl = "https://XXXXX/XX/rest/v1/XXXXX";
try {
    axios.post(reqUrl, form, request_config)
        .then(function (response) {
        console.log(response);
        return callback(response);
     })
    .catch(function (error) {
        console.log(error);
        return callback(error);
    });
} catch (ex) {
  console.log("exception   ", ex);
}

Tried using pipe, and most of possible solutions. file is exist. Not understanding what going wrong here. anything in Readstream ? Thanks for help.

Pravin Bhapkar
  • 463
  • 1
  • 5
  • 15
  • Are you using TypeScript at all? If not, you really should - it's veritably impossible to write non-trivial application code without type annotations. – Dai Sep 17 '20 at 13:00
  • Are you certain your target endpoint supports `multipart/form-data` requests rather than putting files in the request body directly? (Because it isn't commonplace for RESTful web-services to accept data in `multipart/form-data` bodies). – Dai Sep 17 '20 at 13:04

2 Answers2

26

After spending much time and tried lots of possible things, I observed error that I am getting is.

TypeError: data should be a string, Buffer or Uint8Array

and in my formData I am appending one more variable with file is

form.append('extractArchive', false);

This is nothing but boolean and axios or formData is giving error for this. I changed it to,

form.append('extractArchive', 'false');

That solved my issue. may it will help if someone running is such problem.

Thanks for your help.

Pravin Bhapkar
  • 463
  • 1
  • 5
  • 15
1

This line:

axios.post(reqUrl, form, request_config)

You're passing a FormData object in the form argument. Axios (when used from within NodeJS) expects string, Buffer, or Uint8Array.

When using Axios inside a browser it just wraps fetch which allows FormData to be used directly), however when used inside NodeJS you'll need to serialize your own request body (and serializing to multipart/form-data can be painful, owing to Boundary fields, etc).

Assuming that you actually want to make a multipart/form-data request then:

Dai
  • 141,631
  • 28
  • 261
  • 374
  • Hi, Github issue: https://github.com/axios/axios/issues/789 It saying there is no native support. Browser only: FormData, File, Blob // - Node only: Stream data: { firstName: 'Fred' }, I am trying it from Node.js service. – Pravin Bhapkar Sep 17 '20 at 13:17
  • @PravinBhapkar What about it? – Dai Sep 17 '20 at 13:18