我正在嘗試通過 HTTP 流式傳輸價格資料(不知道他們為什么不使用 websockets..)并且我使用 axios 發出正常的 REST API 請求,但我不知道如何處理“傳輸編碼”:' chunked 型別的請求。
此代碼只是掛起并且不會產生任何錯誤,因此假設它正在作業但無法處理回應:
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
感謝你的幫助。
作業解決方案:正如下面的答案所指出的,我們需要添加一個 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)
})
uj5u.com熱心網友回復:
僅供參考,發送content-typeGET 請求的標頭是沒有意義的。content-type 標頭適用于 http 請求的 BODY,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");
});
Axios 檔案參考這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449834.html
標籤:javascript 节点.js http axios
