axios / fetch 实现 stream 流式请求

axios 是一个支持node端和浏览器端的易用、简洁且高效的http库。本文主要介绍 axios 如何实现 stream 流式请求,注意这里需要区分 node 环境和浏览器环境。

一、node端

代码演示:

js 复制代码
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) => {
    // 处理流数据的逻辑
  });

  response.data.on('end', () => {
    // 数据接收完成的逻辑
  });

}); 

二、浏览器端

在浏览器端,axios 是使用 XMLHttpRequest 对象来实现请求,设置 responseType: 'stream' 后会出现以下警告⚠️:
The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType.

所以,在浏览器端,我们需要使用浏览器内置API fetch 来实现 stream 流式请求。

代码演示:

js 复制代码
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);
  }
}

欢迎访问:天问博客

相关推荐
yeapT41 分钟前
网络传输协议的介绍——SSE
网络·websocket·http
QT 小鲜肉1 小时前
【QT/C++】Qt网络编程进阶:UDP通信和HTTP请求的基本原理和实际应用(超详细)
c语言·网络·c++·笔记·qt·http·udp
Jerry2505094 小时前
怎么才能实现网站HTTPS访问?
网络协议·http·网络安全·https·ssl
2501_915918416 小时前
Fiddler抓包工具详解,HTTP/HTTPS抓包、代理设置与调试技巧一站式教程(含实战案例)
http·ios·小程序·https·fiddler·uni-app·webview
null_null9998 小时前
宝塔nginx http转https代理
nginx·http·https
冰糖拌面8 小时前
GO写的http服务,清空cookie
服务器·http·golang
爱编程的鱼8 小时前
HTTP 是什么?它是如何工作的
网络·网络协议·http
檐下翻书17310 小时前
Spring Boot 深度剖析:从虚拟线程到声明式 HTTP 客户端,再到云原生最优解
spring boot·http·云原生
雪域迷影20 小时前
C#中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·http·c#·get
2501_915918411 天前
HTTP抓包工具推荐,Fiddler使用教程、代理设置与调试技巧详解(含HTTPS配置与实战案例)
http·ios·小程序·https·fiddler·uni-app·webview