Jat*_*t90 19 javascript http node.js axios
我正在尝试通过 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)
jfr*_*d00 31
仅供参考,发送content-typeGET 请求的标头是没有意义的。内容类型标头适用于 http 请求的正文,而 GET 请求没有正文。
使用该axios()库,如果您想直接访问响应流,您可以使用该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 => {
console.log(data);
});
stream.on('end', () => {
console.log("stream done");
});
Run Code Online (Sandbox Code Playgroud)
axios文档参考这里。