为什么要用
普通sse是get请求,但是当请求要有token鉴权操作的时候,将token放到请求头并不合理,于是乎有了通过post实现sse的方案
如何使用
安装
npm install @microsoft/fetch-event-source
用法很简单,注意事项我都在注释上备注好了
import { fetchEventSource } from "@microsoft/fetch-event-source";
// 用于中断会话,中断时调用cancelTokenSourceRef.current.abort();
const cancelTokenSourceRef = useRef(new AbortController());
cancelTokenSourceRef.current = new AbortController();
await fetchEventSource(url, {
method: "post",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
Authorization: `Bearer ${localStorage.getItem(ACCESS_TOKEN_KEY)}`,
"Transfer-Encoding": "chunked",
},
body: JSON.stringify(requestBody),
signal: cancelTokenSourceRef.current.signal,
async onopen(response) {
if (response.ok) {
// 成功建立连接
return;
} else {
// 后端报500等情况
const error = await response.json();
throw new Error(error.detail);
}
},
onmessage(msg) {
},
onerror(err) {
// onopen抛出的异常在onerror也要抛,否则会不断触发重连
throw err;
},
onclose() {
},
// 不设置的话用户离开当前页面会触发重连
openWhenHidden: true,
});