@microsoft/fetch-event-source EventSource相关示例文档

本文介绍了如何在前端使用FetchEventSourceAPI与后端的服务器发送事件源(SSE)进行实时通信,包括参数配置、回调函数和CORS设置。同时提供了一个服务器代码示例和前端代码片段作为实践参考。
摘要由CSDN通过智能技术生成
参数说明
参数名描述
headers仅支持字符串键值对 { “xx”: “xx”}
onopen成功链接时回调
onmessage服务器返回消息回调 返回{ data,event,id,retry } ,data即服务器返回数据
onclose响应完成回调
onerror发生任何错误的回调,并会自动在1s后重新尝试目前测试函数体内throw err;会阻断重试
openWhenHidden页面文档被隐藏时会关闭sse链接并在显示时重连 true
无论隐藏与否都不关闭
fetch默认 window.fetch
服务器代码示例
const http = require('http');

const server = http.createServer((req, res) => {

  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

  if (req.method === 'OPTIONS') {
    res.setHeader('Allow', 'GET, POST, PUT, DELETE, OPTIONS');
    res && res.sendStatus && res.sendStatus(200);
  }
  
  if (req.url === '/sse') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive'
    });

    let count = 0;

    let timer = setInterval(() => {
      count++;
      res.write(`data: ${Date.now()}\n\n`);

      if (count >= 5) {
        clearInterval(timer);
        res.end();
      }
    }, 1000); 
  } else {
    res.writeHead(404);
    res.end();
  }
});

server.listen(3000, () => {
  console.log('Server listening on port 3000...');
});
前端代码示例
<template>
  <div>
  </div>
</template>

<script setup>
import { fetchEventSource } from '@microsoft/fetch-event-source';


const ctrl = new AbortController();
fetchEventSource('http://localhost:3000/sse', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
  	a: 1,
  	b: 2,
  }),
  signal: ctrl.signal,
  openWhenHidden: true,
  async onopen(response) {
    console.log('onopen',response);
  },
  onmessage(msg) {
    console.log('fetchEventSource:', msg);
  },
  onclose() {
    console.log('onclose');
  },
  onerror(err) {
    console.log('onerror', err);
    ctrl.abort();
    throw err;
  }
});

</script>



  • 12
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惊悚的毛毛虫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值