Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST binary data in request using request library? [duplicate]

I have to send binary contents of a remote file to an API endpoint. I read the binary contents of remote file using request library and store it in a variable. Now with contents in the variable ready to be sent, how do I post it to remote api using request library.

What I have currently and doesn't work is:

const makeWitSpeechRequest = (audioBinary) => {
  request({
    url: 'https://api.wit.ai/speech?v=20160526',
    method: 'POST',
    body: audioBinary,
  }, (error, response, body) => {
    if (error) {
      console.log('Error sending message: ', error)
    } else {
      console.log('Response: ', response.body)
    }
  })
}

We can safely assume here that audioBinary has binary contents that were read from a remote file.

What do I mean when I say it doesn't work?
The payload shows up different in request debugging. Actual binary payload: ID3TXXXmajor_brandisomTXXXminor_version512TXXX
Payload showed in debugging: ID3\u0004\u0000\u0000\u0000\u0000\u0001\u0006TXXX\u0000\u0000\u0000\

What works in Terminal?
What I know works from Terminal is with a difference that it reads the contents of file too in the same command:

curl -XPOST 'https://api.wit.ai/speech?v=20160526' \
      -i -L \
      --data-binary "@hello.mp3"
like image 732
Priya Ranjan Singh Avatar asked Jun 08 '16 13:06

Priya Ranjan Singh


1 Answers

The option in request library to send binary data as such is encoding: null. The default value of encoding is string so contents by default get converted to utf-8.

So the correct way to send binary data in the above example would be:

const makeWitSpeechRequest = (audioBinary) => {
  request({
    url: 'https://api.wit.ai/speech?v=20160526',
    method: 'POST',
    body: audioBinary,
    encoding: null
  }, (error, response, body) => {
    if (error) {
       console.log('Error sending message: ', error)
    } else {
      console.log('Response: ', response.body)
    }
  })
}
like image 164
Priya Ranjan Singh Avatar answered Nov 04 '22 20:11

Priya Ranjan Singh