1

I have call an API from my javascript code using the requests package. But since it is deprecated, I want to replace it with axios.

The call is like this:

request({
  url: 'the_url',
  method: 'POST',
  encoding: null,
  headers: {
    'Content-Type': 'application/x-protobuf',
    'Connection': 'Keep-Alive',
    'Accept-Encoding': 'gzip',
  },
  body: requestBody,
}, callback);

Where the requestBody is Uint8Array I create with the data I need to send. The above works ok and I get the response I need. However, when I re-write this to axios like this

axios({
    url: 'the_url',
    method: 'POST',
    encoding: null,
    headers: {
      'Content-Type': 'application/x-protobuf',       
      'Connection': 'Keep-Alive',
      'Accept-Encoding': 'gzip',
    },
    data: requestBody,
  }
).then( (res) => {
  console.log(res);
}).catch( (error) => {
  console.log(error);
})

The server returns a 500 error. It is the exact same URL and same requestBody variable.

EDIT: When I inspect the actual request objects for both cases, it looks the passed requestBody doesn't have the exact same format.

In the case of request, it is like this:

body: <Buffer 22 07 ... ... 396 more bytes>

But in case of axios like this

data: ArrayBuffer {
  [Uint8Contents]: <22 07 ... ... 346 more bytes>,
  byteLength: 446
}

Nothing changes in the creation of the requestBody. I pass exactly the same parameter in both cases. So, it has to be something related to how axios and requests handle those cases.

Tasos
  • 7,325
  • 18
  • 83
  • 176

1 Answers1

0

Try this

let formData = new FormData()

formdata.append('reqBody', requestBody)

axios({
    url: 'the_url',
    method: 'POST',
    encoding: null,
    headers: {
      'Content-Type': 'multipart/form-data',       
      'Connection': 'Keep-Alive',
      'Accept-Encoding': 'gzip',
    },
    data: formdata,
  }
).then( (res) => {
  console.log(res);
}).catch( (error) => {
  console.log(error);
})
DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
  • 1
    Getting this `UnhandledPromiseRejectionWarning: TypeError: source.on is not a function` which Google says you get when the FormData is not an object :( – Tasos Jun 14 '21 at 13:21