首页 > web前端 > js教程 > 正文

使用 Axios 处理 Server-Sent Events (SSE) 的响应

心靈之曲
发布: 2025-09-24 18:58:19
原创
272人浏览过

使用 axios 处理 server-sent events (sse) 的响应

本文档旨在指导开发者如何使用 Axios 在 Web 浏览器环境中处理 Server-Sent Events (SSE) 类型的 API 响应。由于 EventSource 不支持 POST 请求,我们将探讨如何利用 Axios 的 onDownloadProgress 属性来读取 SSE 数据流,并介绍 fetch-event-source 库的替代方案。此外,还将提供服务端 Java 代码示例,展示如何使用 Spring WebClient 处理 SSE。

前端:使用 Axios 读取 SSE 数据流

当需要通过 POST 请求与 SSE API 进行交互时,传统的 EventSource 接口不再适用。我们可以利用 Axios 提供的 onDownloadProgress 回调函数来逐段读取服务器推送的数据。

以下是一个使用 Axios 处理 SSE 响应的示例:

axios({
  url: '/my-service/chat', // 你的 API 地址
  method: 'POST',
  data: {
    model: "gpt-3.5-turbo",
    prompt: "Say this is a test",
    max_tokens: 7,
    steam: true,
    temperature: 0
  },
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'text/event-stream', // 声明接受 SSE 数据流
    'SESSION_ID': 'Header-Value'
  },
  onDownloadProgress: progressEvent => {
    const xhr = progressEvent.event.target;
    const { responseText } = xhr;
    console.log("=====responseText======");
    console.log(responseText);
    // 在这里处理接收到的数据,例如解析 SSE 格式的数据
  }
}).then(({ data }) => {
  // 请求成功完成后的处理,注意,这里可能不会接收到完整的数据,而是接收到 Axios 自身的响应数据结构。
  console.log("请求完成", data);
}).catch(error => {
    console.error("请求出错", error);
});
登录后复制

代码解释:

  1. url: 指定 SSE API 的地址。
  2. method: 设置为 'POST',以发送 POST 请求。
  3. data: 包含要发送到服务器的数据。
  4. headers:
    • Content-Type: 设置为 'application/json',表明发送的数据是 JSON 格式。
    • Accept: 设置为 'text/event-stream',告知服务器客户端期望接收 SSE 数据流。
    • SESSION_ID: 示例的自定义 Header。
  5. onDownloadProgress: 这个回调函数会在接收到服务器推送的数据时被触发。progressEvent.event.target.responseText 包含了当前接收到的所有数据。你需要在此处解析 SSE 格式的数据,并进行相应的处理。

注意事项:

  • responseText 包含了从连接建立开始到当前时刻的所有数据。这意味着你需要自己处理数据的分割和解析,以提取出单个 SSE 事件。
  • responseType: 'stream' 属性在浏览器环境中通常不直接支持,因此省略。
  • 服务器端需要正确设置 Content-Type 为 text/event-stream,并按照 SSE 协议推送数据。

替代方案:使用 fetch-event-source

fetch-event-source 是一个专门用于处理 SSE 的 JavaScript 库,它提供了更方便的 API 来处理 SSE 数据流。

你可以通过 npm 安装它:

AppMall应用商店
AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

AppMall应用商店 56
查看详情 AppMall应用商店
npm install fetch-event-source
登录后复制

然后,你可以使用以下代码来处理 SSE 响应:

import { fetchEventSource } from '@microsoft/fetch-event-source';

const url = '/my-service/chat';
const data = {
  model: "gpt-3.5-turbo",
  prompt: "Say this is a test",
  max_tokens: 7,
  steam: true,
  temperature: 0
};

fetchEventSource(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'text/event-stream',
    'SESSION_ID': 'Header-Value'
  },
  body: JSON.stringify(data),
  onmessage(event) {
    console.log("Received SSE message:", event.data);
    // 处理接收到的 SSE 事件
  },
  onerror(error) {
    console.error("SSE error:", error);
    // 处理错误
  },
  onclose() {
    console.log("SSE connection closed");
    // 连接关闭后的处理
  }
});
登录后复制

代码解释:

  • fetchEventSource 函数接收 URL 和一个配置对象作为参数。
  • method、headers 和 body 属性与 Axios 的配置类似。
  • onmessage 回调函数会在接收到 SSE 事件时被触发,event.data 包含事件的数据。
  • onerror 回调函数会在发生错误时被触发。
  • onclose 回调函数会在连接关闭时被触发。

后端:Spring WebClient 处理 SSE

以下是一个使用 Spring WebClient 处理 SSE 的 Java 代码示例:

import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

public class SseClient {

    public void consumeServerSentEvent() {
        WebClient client = WebClient.create("http://localhost:8080"); // 你的服务器地址

        Flux<ServerSentEvent<String>> eventStream = client.get()
                .uri("/stream-sse") // SSE endpoint
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(ServerSentEvent.class);

        eventStream.subscribe(
                content -> System.out.println("Time: " + java.time.LocalTime.now() +
                        " - event: name[" + content.event() + "], id [" + content.id() + "], content[" + content.data() + "]"),
                error -> System.err.println("Error receiving SSE: " + error),
                () -> System.out.println("Completed!!!"));
    }
}
登录后复制

代码解释:

  1. WebClient.create(): 创建一个 WebClient 实例,指定服务器的地址。
  2. uri("/stream-sse"): 指定 SSE endpoint 的 URI。
  3. accept(MediaType.TEXT_EVENT_STREAM): 设置 Accept header 为 text/event-stream。
  4. retrieve().bodyToFlux(ServerSentEvent.class): 将响应体转换为 Flux<ServerSentEvent<String>>,以便异步处理 SSE 事件。
  5. subscribe(): 订阅 Flux,并提供三个回调函数:
    • onNext: 在接收到新的 SSE 事件时被调用。
    • onError: 在发生错误时被调用。
    • onComplete: 在连接关闭时被调用。

总结:

本文介绍了使用 Axios 和 fetch-event-source 在前端处理 SSE 响应的方法,以及使用 Spring WebClient 在后端处理 SSE 的方法。选择哪种方法取决于你的具体需求和项目环境。使用 Axios 时需要手动解析数据流,而 fetch-event-source 提供了更方便的 API。在后端,Spring WebClient 提供了强大的异步处理能力,可以轻松地处理 SSE 数据流。

以上就是使用 Axios 处理 Server-Sent Events (SSE) 的响应的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号