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

欢迎访问:天问博客

相关推荐
To_OC6 小时前
从一头雾水到跑通全流程:我用一个周末啃透了JWT登录鉴权
前端·后端·http
小贺儿开发19 小时前
Unity 局域网遥控幻灯片展示工具 3.0
科技·http·unity·工具·ppt·通信·网页
剑锋所指,所向披靡!2 天前
HTTP服务器的基本相关概念
服务器·网络协议·http
可乐鸡翅yeah_2 天前
新手梳理:HLS 线上问题,哪些该提给 CDN,哪些该找后端切片服务
开发语言·前端·javascript·vue.js·网络协议·http·m3u8在线
m0_738185822 天前
Flutter 鸿蒙化实战:http_proxy 适配 OpenHarmony,HTTP 代理
flutter·http·华为·harmonyos·鸿蒙
91刘仁德2 天前
HTTP协议详解:从URL到HTTP服务器的完整实战
服务器·网络·笔记·网络协议·http
可乐鸡翅yeah_2 天前
hls.js 手动自定义 http 请求 loader,修改请求头实战
开发语言·前端·javascript·网络协议·http·ecmascript·m3u8在线
AIgorithmGEEK3 天前
[Linux]HTTP 应用层协议全解(下篇)
linux·网络·网络协议·http·cookie·无连接·无状态
AIgorithmGEEK3 天前
[Linux]HTTP 应用层协议全解(中篇)
linux·网络·网络协议·http
91刘仁德3 天前
HTTPS 加密原理与 CA 数字证书:从对称加密到完整通信流程
网络·笔记·网络协议·http·https