axios/fetch實現(xiàn)stream流式請求示例詳解
axios簡介
axios 是一個支持node端和瀏覽器端的易用、簡潔且高效的http庫。本文主要介紹 axios / fetch 如何實現(xiàn) stream 流式請求,注意這里需要區(qū)分 node 環(huán)境和瀏覽器環(huán)境。
node端
代碼演示:
const axios = require('axios');
axios({
method: 'get',
url: 'http://tiven.cn/static/img/axios-stream-01-kcUzNdZO.jpg',
responseType: 'stream'
})
.then(response => {
response.data.on('data', (chunk) => {
// 處理流數(shù)據(jù)的邏輯
});
response.data.on('end', () => {
// 數(shù)據(jù)接收完成的邏輯
});
}); 瀏覽器端
在瀏覽器端,axios 是使用 XMLHttpRequest 對象來實現(xiàn)請求,設置 responseType: 'stream' 后會出現(xiàn)以下警告??:
The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType.
所以,在瀏覽器端,我們需要使用瀏覽器內(nèi)置API fetch 來實現(xiàn) stream 流式請求。
代碼演示:
async function getStream() {
try {
let response = await fetch('/api/admin/common/testStream');
console.log(response);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const reader = response.body.getReader();
const textDecoder = new TextDecoder();
let result = true;
let output = ''
while (result) {
const { done, value } = await reader.read();
if (done) {
console.log('Stream ended');
result = false;
break;
}
const chunkText = textDecoder.decode(value);
output += chunkText;
console.log('Received chunk:', chunkText);
}
} catch (e) {
console.log(e);
}
}以上就是axios / fetch 實現(xiàn) stream 流式請求的詳細內(nèi)容,更多關于axios / fetch 實現(xiàn) stream 流式請求的資料請關注腳本之家其它相關文章!
相關文章
JavaScript使用indexOf獲得子字符串在字符串中位置的方法
這篇文章主要介紹了JavaScript使用indexOf獲得子字符串在字符串中位置的方法,涉及javascript中indexOf方法操作字符串的技巧,需要的朋友可以參考下2015-04-04
JavaScript實現(xiàn)自己的DOM選擇器原理及代碼
實現(xiàn)自己的DOM選擇器時匹配行為也應該和瀏覽原生匹配行為一致,接下來本文將詳細介紹下實現(xiàn)思路及方法,感興趣的你可以參考下或許對你鞏固知識有所幫助2013-03-03

