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

8
我需要将远程文件的二进制内容发送到API端点。我使用request库读取了远程文件的二进制内容并将其存储在变量中。现在,当变量中的内容准备好被发送时,我该如何使用request库将其发布到远程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)
    }
  })
}

我们可以安全地假设这里的包含了从远程文件中读取的二进制内容。
当我说它不起作用时,我是什么意思呢?
有效载荷在请求调试中显示不同。
实际的二进制有效载荷: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"

你有没有成功? - Utkarsh
是的,我会在这里发布答案。答案在文档中。 - Priya Ranjan Singh
1个回答

10

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

3
请确保传递给请求的选项中json属性未设置为true,因为这会覆盖encoding: null并导致将响应体视为文本。 - alphaloop
1
在我的情况下,不设置 encoding: null 也可以工作。请注意,设置 encoding: null 将返回二进制响应。 - Raptor
1
你是如何读取那个文件的?使用 fs.createReadStream('文件路径', { encoding: 'binary' }) 还是其他方式? - Kasir Barati

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接