2016-06-08 158 views
2

我必须将远程文件的二进制内容发送到API端点。我使用request library读取远程文件的二进制内容并将其存储在一个变量中。现在,变量中的内容已准备好发送,如何使用请求库将它发布到远程API。如何使用请求库在请求中POST二进制数据?

我有什么当前,不工作是:

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" 
+0

你得到任何的成功吗? – Utkarsh

+0

是的,我会在这里发布答案。答案在文档中。 –

回答

2

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

还要确保传递给请求的选项中的'json'属性没有设置为'true',因为这将覆盖'encoding:null'并导致将该正文视为文本。 – alphaloop