
本文档旨在指导开发者如何使用 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);});
代码解释:
url: 指定 SSE API 的地址。method: 设置为 ‘POST’,以发送 POST 请求。data: 包含要发送到服务器的数据。headers:Content-Type: 设置为 ‘application/json’,表明发送的数据是 JSON 格式。Accept: 设置为 ‘text/event-stream’,告知服务器客户端期望接收 SSE 数据流。SESSION_ID: 示例的自定义 Header。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 安装它:
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> 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!!!")); }}
代码解释:
WebClient.create(): 创建一个 WebClient 实例,指定服务器的地址。uri(“/stream-sse”): 指定 SSE endpoint 的 URI。accept(MediaType.TEXT_EVENT_STREAM): 设置 Accept header 为 text/event-stream。retrieve().bodyToFlux(ServerSentEvent.class): 将响应体转换为 Flux>,以便异步处理 SSE 事件。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) 的响应的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1522553.html
微信扫一扫
支付宝扫一扫