欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

axios/fetch實現(xiàn)stream流式請求示例詳解

 更新時間:2023年09月20日 12:00:27   作者:天問  
這篇文章主要為大家介紹了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)請求,設(shè)置 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)容,更多關(guān)于axios / fetch 實現(xiàn) stream 流式請求的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論