Pri*_*ngh 5 javascript binary post request requestjs
我必须将远程文件的二进制内容发送到API端点.我使用请求库读取远程文件的二进制内容并将其存储在变量中.现在变量中的内容已准备好发送,如何使用请求库将其发布到远程api.
我现在和不起作用的是:
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)
}
})
}
Run Code Online (Sandbox Code Playgroud)
我们可以安全地假设这里audioBinary有从远程文件中读取的二进制内容.
当我说它不起作用时,我的意思是什么?
有效负载在请求调试中显示不同.实际二进制有效负载:ID3TXXXmajor_brandisomTXXXminor_version512TXXX
调试时显示有效负载:ID3\u0004\u0000\u0000\u0000\u0000\u0001\u0006TXXX\u0000\u0000\u0000\
什么在终端有效?
我所知道的终端工作的不同之处在于它也在同一个命令中读取文件的内容:
curl -XPOST 'https://api.wit.ai/speech?v=20160526' \
-i -L \
--data-binary "@hello.mp3"
Run Code Online (Sandbox Code Playgroud)
请求库中发送二进制数据的选项是encoding: null.编码的默认值是string默认情况下转换为内容的内容utf-8.
因此,在上面的例子中发送二进制数据的正确方法是:
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)
}
})
}
Run Code Online (Sandbox Code Playgroud)