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

欢迎访问:天问博客

相关推荐
右耳朵猫AI6 小时前
Go周刊2026W36 | Go 1.27.1 发布、TinyGo 0.42、HTTP/2 原生迁入 net/http、quic-go 0.62
redis·http·golang
承渊政道15 小时前
星空组网真实体验:Mac远程访问Ubuntu,SSH与HTTP全流程验证
ubuntu·http·macos·ssh·服务器管理·星空组网
牛油果子哥q2 天前
C++对接LLM完整工程:异步HTTP请求、JSON解析、超时容错、重连兜底
c++·http·json
SKH.2 天前
网络(4)HTTP协议与TCP并发服务器
网络·tcp/ip·http
你不是我我2 天前
【AI 测评】群晖 NAS 部署 Vaultwarden:从 HTTPS 到浏览器自动填充的完整密码管理流程
网络协议·http·https
IT大白鼠2 天前
Ingress 与 Ingress-Controller:K8s 七层 HTTP 反向代理技术详解与实践
http·容器·kubernetes
myy-learn2 天前
30-HTTP协议
网络·网络协议·http
G佳伟3 天前
宝塔面板打不开且 Bt-Panel 未运行:从 HTTP 502 到 gevent 缺失的完整排查与修复
网络协议·http·php
keyipatience3 天前
IP网络层
服务器·网络·网络协议·ubuntu·http
白狐_7983 天前
408 计算机网络|HTTP 的 RTT 怎么数:用多道题讲清楚
网络协议·计算机网络·http