How to POST binary data in request using request library?
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)
}
})
}
Comments
-
Priya Ranjan Singh almost 2 years
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"
-
alphaloop over 6 yearsAlso make sure that the
json
property in the options passed to the request isn't set totrue
as this will override theencoding: null
and cause the body to be treated as text. -
Raptor about 5 yearsIt worked without setting
encoding: null
in my case. Note that settingencoding: null
returns binary response. -
Kasir Barati over 3 yearsHow do you read that file?
fs.createReadStream('path-to-file', { encoding: 'binary' })
or something else?