SSE event-source-polyfill 前后台建立通信 和@microsoft/fetch-event-source(消息推送)

1‌.1 安装库‌ event-source-polyfill (不支持post)

npm install event-source-polyfill

1.2 代码实现

import { EventSourcePolyfill } from 'event-source-polyfill';

const sse = new EventSourcePolyfill('https://api.xxx.com/sse', {//换成自己的后台地址
  headers: { 'Authorization': 'Bearer your_token' },  // 自定义请求头‌:ml-citation{ref="1,6" data="citationList"}
  withCredentials: true  // 跨域时携带 Cookie‌:ml-citation{ref="6" data="citationList"}
});

sse.onmessage = (event) => {
  console.log('Received:', event.data);
};

// 关闭连接
sse.close();

在这里插入图片描述

2.1 安装库‌ @microsoft/fetch-event-source (支持get和post)

npm install @microsoft/fetch-event-source

2.2 代码实现

import { fetchEventSource } from '@microsoft/fetch-event-source';


const sseInit = () => {
  fetchEventSource('/dev-api/xxxx/sse', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      // 'Authorization': 'Bearer YOUR_TOKEN',
    },
    body: JSON.stringify({
      "request_id": "1",
      "content": "测试", 
    }),
    onopen(response) {
      // 连接成功时触发
      if (response.ok) return;
      throw new Error('连接失败');
    },
    onmessage(event) {
      // 接收服务器发送的每条事件
      console.log('收到数据:', event.data); 
    },
    onclose() {
      // 连接关闭时触发
      console.log('连接终止');
    },
    onerror(err) {
      // 错误处理(默认会抛出异常并自动重试)
      console.error('错误:', err);
      throw err; // 抛出错误会触发重试机制
    }
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值