8

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"
Priya Ranjan Singh
  • 1,567
  • 1
  • 15
  • 29

1 Answers1

10

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)
    }
  })
}
Priya Ranjan Singh
  • 1,567
  • 1
  • 15
  • 29
  • 3
    Also make sure that the `json` property in the options passed to the request isn't set to `true` as this will override the `encoding: null` and cause the body to be treated as text. – alphaloop Jan 20 '18 at 18:52
  • 1
    It worked without setting `encoding: null` in my case. Note that setting `encoding: null` returns binary response. – Ahsan Mar 30 '19 at 23:15
  • 1
    How do you read that file? `fs.createReadStream('path-to-file', { encoding: 'binary' })` or something else? – Kasir Barati Sep 24 '20 at 06:55