
本文档旨在指导开发者如何使用 Axios 在 Web 浏览器环境中处理 Server-Sent Events (SSE)。由于 EventSource 不支持 POST 请求,我们将探讨使用 Axios 配合 onDownloadProgress 事件来接收和处理 SSE 数据流,并提供其他替代方案,例如 fetch-event-source 库以及服务端实现的示例。
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));代码解释:
注意事项:
除了使用 Axios 和 onDownloadProgress 之外,还有其他一些方法可以处理 SSE:
以下是使用 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;
@RestController
public class SSEController {
@GetMapping(value = "/stream-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamEvents() {
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> ServerSentEvent.<String>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<String>> 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) 的方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号