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);
  }
}

欢迎访问:天问博客

相关推荐
YYYing.1 小时前
【C++大型项目之高性能服务器框架 (九) 】协议抽象与Http服务器模块
服务器·c++·http·高性能·c/c++·后端框架
_waylau2 小时前
Spring Framework HTTP服务客户端详解
java·后端·网络协议·spring·http·spring cloud
Android-Flutter2 小时前
Android的http和https知识点
android·http·https
爱刷碗的苏泓舒2 小时前
网络通信入门之 NTRIP、HTTP、TCP 与 IP 的关系:协议分层、连接过程以及实时数据流
网络协议·tcp/ip·http·网络通信·rtcm·监控运维·ntrip
我星期八休息12 小时前
网络编程—应用层HTTP协议
linux·运维·开发语言·前端·网络·网络协议·http
Re_Virtual19 小时前
基于web的轻量级http测试工具——Restfox
http·docker·开源·restfox
ControlRookie1 天前
输入一个 URL 以后,一次 HTTP 事务经历了什么
http·工业通信·codesys·工业自动化·plc通信
Tsuki_tl1 天前
【面试高频】HTTPS加密传输过程
http·https·非对称加密·数字证书·对称加密·ca证书·中间人攻击
meilindehuzi_a1 天前
浏览器端 HTTP 流式通信详解:从 SSE 到 EventSource、fetch 与 ReadableStream
网络·网络协议·http
Sagittarius_A*1 天前
Open HTTP Redirect 开放重定向漏洞:URL 跳转校验缺陷与绕过技术
网络·安全·web安全·http·dvwa·burp suite