实现服务器发送事件(Server-Sent Events, SSE)通信:
原生 EventSource | @microsoft/fetch-event-source | |
HTTP 方法 | 仅支持 GET | 支持 |
请求控制 | 无法主动取消请求(依赖浏览器原生行为) | 支持 AbortController 主动终止连接 |
请求头/Body | 仅支持部分简单请求头(如 Authorization ) | 支持自定义请求头、请求体(如 POST 数据) |
错误处理 | 有限的重连控制(默认自动重连) | 可自定义重连策略(如指数退避) |
兼容性 | 现代浏览器(IE 不支持) | 依赖 fetch 和 AbortController (现代浏览器) |
npm install @microsoft/fetch-event-source
import React, { useRef } from 'react'
//fetchEventSource:微软实现的 SSE 客户端库
import { fetchEventSource } from '@microsoft/fetch-event-source'
const index=()=>{
//创建一个可变的引用对象 controllerRef,用于存储 AbortController实例
const controllerRef = useRef(null);
.
.
.
.
const handleFlu=()=>{
controllerRef.current = new AbortController();
const eventSource = fetchEventSource(接口, {
method: 'POST',
headers:{
'Content-Type': 'application/json',
}
body: JSON.stringify({
a:'搜索数据'
}),
signal: controllerRef.current.signal,
openWhenHidden: true,
onopen: (e) => {
// 建立连接的回调
},
onmessage: (e) => {
//此处应添加数据处理逻辑(如更新状态、渲染 UI 等)
const res = JSON.parse(e.data)
const {data}=res//此处解构出来的md数据可以通过md插件进行渲染
}
onclose: () => {
controllerRef.current.abort();//// 主动终止请求
eventSource.close();//// 关闭连接
},
onerror: () => {
controllerRef.current.abort();// 错误时终止请求
eventSource.close();
},
}
}