@microsoft/fetch-event-source实现sse流式功能

本文介绍了在需要鉴权的Server-SentEvents(SSE)场景中,如何通过POST请求替代GET,并使用`fetch-event-source`库进行安装和用法说明,包括取消请求和处理错误的示例代码。
摘要由CSDN通过智能技术生成

为什么要用

普通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,
        });
  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值