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

1

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"
Bronnie answered 8/6, 2016 at 13:12 Comment(2)
Did you get any success ?Summerville
Yes, I'll post an answer here. The answer was in the documentation.Bronnie
B
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)
    }
  })
}
Bronnie answered 2/3, 2017 at 18:41 Comment(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.Devereux
It worked without setting encoding: null in my case. Note that setting encoding: null returns binary response.Sjoberg
How do you read that file? fs.createReadStream('path-to-file', { encoding: 'binary' }) or something else?Clapboard

© 2022 - 2024 — McMap. All rights reserved.