我正在尝试通过 HTTP 传输价格数据(不知道他们为什么不使用 websockets..)并且我使用 axios 发出正常的 REST API 请求,但我不知道如何处理“传输编码”:'分块”类型的请求。
此代码只是挂起并且不会产生任何错误,因此假设它正在工作但无法处理响应:
const { data } = await axios.get(`https://stream.example.com`, {headers:
{Authorization: `Bearer ${token}`, 'Content-Type': 'application/octet-
stream'}})
console.log(data) // execution hangs before reaching here
Run Code Online (Sandbox Code Playgroud)
感谢你的帮助。
工作解决方案:正如下面的答案所指出的,我们需要添加一个responseType:流作为axios选项,并在响应上添加一个事件监听器。
工作代码:
const response = await axios.get(`https://stream.example.com`, {
headers: {Authorization: `Bearer ${token}`},
responseType: 'stream'
});
const stream = response.data
stream.on('data', data => {
data = data.toString()
console.log(data)
})
Run Code Online (Sandbox Code Playgroud)