陽春網(wǎng)站開發(fā)鄭州本地seo顧問
axios 是一個(gè)支持node端和瀏覽器端的易用、簡(jiǎn)潔且高效的http庫。本文主要介紹 axios 如何實(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ì)象來實(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
來實(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);}
}
歡迎訪問:天問博客