
本文档旨在指导开发者如何使用 Axios 在 Web 浏览器环境中处理 Server-Sent Events (SSE)。由于 EventSource 不支持 POST 请求,我们将探讨使用 Axios 配合 onDownloadProgress 事件来接收和处理 SSE 数据流,并提供其他替代方案,例如 fetch-event-source 库以及服务端实现的示例。
使用 Axios 和 onDownloadProgress 处理 SSE
Server-Sent Events (SSE) 是一种服务器推送技术,允许服务器向客户端单向实时地发送数据。 通常,EventSource 是处理 SSE 的首选方法,但它仅支持 GET 请求。当需要使用 POST 请求与 SSE API 交互时,我们需要寻找替代方案。
Axios 提供了一个 onDownloadProgress 回调函数,可以在接收响应数据时触发。我们可以利用这个回调函数来逐块地读取 SSE 数据流。
示例代码:
axios({ url: 'https://api', // 替换为你的 SSE API 地址 data: { prompt: 'json data' // 替换为你的 POST 数据 }, headers: { 'accept': '*', // 接受所有类型,确保能接收 text/event-stream 'content-type': 'application/json' // 声明发送的数据类型为 JSON }, method: 'POST', onDownloadProgress: progressEvent => { const xhr = progressEvent.event.target; const { responseText } = xhr; console.log("=====responseText======"); console.log(responseText); // 处理接收到的 SSE 数据 }}).then(({ data }) => Promise.resolve(data));
代码解释:
url: 指定 SSE API 的地址。data: 包含要发送到服务器的 POST 数据。headers:accept: ‘*’:设置 Accept 头以接受任何内容类型。这确保服务器返回的 text/event-stream 可以被客户端接受。content-type: ‘application/json’:声明发送的数据类型为 JSON。method: ‘POST’:指定使用 POST 方法。onDownloadProgress: 这是一个回调函数,在接收到响应数据时被调用。progressEvent.event.target: 提供对 XMLHttpRequest 对象的访问。xhr.responseText: 包含到目前为止接收到的所有响应文本。 每次接收到新的数据块,responseText 都会更新。
注意事项:
responseText 包含到目前为止接收到的所有数据,你需要根据 SSE 协议解析这些数据。 SSE 协议通常使用换行符 (n) 分隔不同的事件。确保服务器正确设置了 Content-Type 响应头为 text/event-stream。根据实际情况调整 accept 头,如果服务器只返回 text/event-stream,则可以将其设置为 ‘text/event-stream’。
其他替代方案
除了使用 Axios 和 onDownloadProgress 之外,还有其他一些方法可以处理 SSE:
fetch-event-source 库: 这是一个专门用于处理 SSE 的 JavaScript 库,它提供了更高级的 API 和错误处理机制。 你可以通过 npm 安装: npm install fetch-event-source。 具体使用方法请参考其 GitHub 仓库:https://www.php.cn/link/f7370a6dcf0258acd5d76f594612c249
服务端实现示例 (Java Spring)
以下是使用 Spring Framework 在服务端实现 SSE 的示例代码:
import org.springframework.http.MediaType;import org.springframework.http.codec.ServerSentEvent;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.reactive.function.client.WebClient;import reactor.core.publisher.Flux;import java.time.LocalTime;import java.time.Duration;@RestControllerpublic class SSEController { @GetMapping(value = "/stream-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent> streamEvents() { return Flux.interval(Duration.ofSeconds(1)) .map(sequence -> ServerSentEvent.builder() .id(String.valueOf(sequence)) .event("periodic-event") .data("Server time: " + LocalTime.now()) .build()); }}
这段代码创建了一个 /stream-sse 端点,它每秒发送一个包含服务器时间的 SSE 事件。
客户端消费示例 (Java Spring WebClient):
import org.springframework.http.codec.ServerSentEvent;import org.springframework.web.reactive.function.client.WebClient;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;import java.time.LocalTime;import java.time.Duration;public class SSEClient { public static void main(String[] args) { WebClient client = WebClient.create("http://localhost:8080"); Flux<ServerSentEvent> eventStream = client.get() .uri("/stream-sse") .retrieve() .bodyToFlux(ServerSentEvent.class); eventStream.subscribe( content -> System.out.println("Time: " + LocalTime.now() + " - event: " + content.event() + ", id: " + content.id() + ", content: " + content.data()), error -> System.err.println("Error receiving SSE: " + error), () -> System.out.println("Completed!!!")); // Keep the program running for a while to receive events try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } }}
总结
虽然 EventSource 是处理 SSE 的标准方法,但在需要使用 POST 请求时,Axios 配合 onDownloadProgress 提供了一种可行的替代方案。 同时,也可以考虑使用 fetch-event-source 库以获得更高级的功能。 最后,服务端也需要正确配置 SSE 端点,并设置正确的 Content-Type 响应头。 通过结合客户端和服务端的正确实现,可以有效地使用 SSE 进行实时数据推送。
以上就是使用 Axios 处理 Server-Sent Events (SSE) 的方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1522549.html
微信扫一扫
支付宝扫一扫