axios/fetch實(shí)現(xiàn)stream流式請(qǐng)求示例詳解
axios簡(jiǎn)介
axios 是一個(gè)支持node端和瀏覽器端的易用、簡(jiǎn)潔且高效的http庫(kù)。本文主要介紹 axios / fetch 如何實(shí)現(xiàn) stream 流式請(qǐng)求,注意這里需要區(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 對(duì)象來(lái)實(shí)現(xiàn)請(qǐng)求,設(shè)置 responseType: 'stream'
后會(huì)出現(xiàn)以下警告??:
The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType.
所以,在瀏覽器端,我們需要使用瀏覽器內(nèi)置API fetch
來(lái)實(shí)現(xiàn) stream 流式請(qǐng)求。
代碼演示:
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 實(shí)現(xiàn) stream 流式請(qǐng)求的詳細(xì)內(nèi)容,更多關(guān)于axios / fetch 實(shí)現(xiàn) stream 流式請(qǐng)求的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于arguments,callee,caller等的測(cè)試
關(guān)于arguments,callee,caller等的測(cè)試...2006-12-12JavaScript使用indexOf獲得子字符串在字符串中位置的方法
這篇文章主要介紹了JavaScript使用indexOf獲得子字符串在字符串中位置的方法,涉及javascript中indexOf方法操作字符串的技巧,需要的朋友可以參考下2015-04-04原生JS實(shí)現(xiàn)獲取及修改CSS樣式的方法
這篇文章主要介紹了原生JS實(shí)現(xiàn)獲取及修改CSS樣式的方法,結(jié)合實(shí)例形式簡(jiǎn)單分析了JavaScript針對(duì)頁(yè)面元素屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-09-09JavaScript實(shí)現(xiàn)自己的DOM選擇器原理及代碼
實(shí)現(xiàn)自己的DOM選擇器時(shí)匹配行為也應(yīng)該和瀏覽原生匹配行為一致,接下來(lái)本文將詳細(xì)介紹下實(shí)現(xiàn)思路及方法,感興趣的你可以參考下或許對(duì)你鞏固知識(shí)有所幫助2013-03-03js實(shí)現(xiàn)屏幕自適應(yīng)局部代碼分享
這篇文章主要介紹了js實(shí)現(xiàn)屏幕自適應(yīng)局部代碼分享,需要的朋友可以參考下2015-01-01BootstrapValidator超詳細(xì)教程(推薦)
這篇文章主要介紹了BootstrapValidator超詳細(xì)教程(推薦)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12