【问题标题】:How to POST binary data in request using request library? [duplicate]如何使用请求库在请求中发布二进制数据? [复制]
【发布时间】:2016-06-08 13:12:13
【问题描述】:

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

【问题讨论】:

  • 你成功了吗?
  • 是的,我会在这里发布答案。答案在文档中。

标签: javascript post binary request requestjs


【解决方案1】:

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

【讨论】:

  • 还要确保传递给请求的选项中的json 属性未设置为true,因为这将覆盖encoding: null 并导致正文被视为文本。
  • 在我的情况下,它在没有设置 encoding: null 的情况下工作。请注意,设置 encoding: null 返回二进制响应。
  • 您是如何阅读该文件的? fs.createReadStream('path-to-file', { encoding: 'binary' }) 还是别的什么?
猜你喜欢
  • 1970-01-01
  • 2014-07-15
  • 2012-02-15
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
相关资源
最近更新 更多