如何使用请求库在请求中 POST 二进制数据?

How to POST binary data in request using request library?

我必须将远程文件的二进制内容发送到 API 端点。我使用 request library 读取远程文件的二进制内容并将其存储在一个变量中。现在变量中的内容已准备好发送,我如何 post 使用请求库将其 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)
    }
  })
}

我们可以在这里安全地假设 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"

请求库中发送二进制数据的选项是 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)
    }
  })
}