fetchEventSource
是一个用于处理 Server-Sent Events (SSE) 的函数,通常用于从服务器接收实时更新。它允许客户端通过 HTTP 连接接收服务器推送的消息。
1.Server-Sent Events (SSE):
-
SSE 是一种允许服务器向浏览器推送实时更新的技术。
-
它使用单向的 HTTP 连接,服务器可以随时向客户端发送数据。
-
SSE 适用于需要频繁更新的应用场景,如实时通知、ai对话等
2.fetchEventSource:
1.fetchEventSource
是一个用于处理 SSE 的库函数,通常用于封装和简化 SSE 的使用。
2.它提供了更现代和灵活的方式来处理 SSE,支持流式数据处理和错误处理。
首先下载插件:
- npm install --save @microsoft/fetch-event-source
import { fetchEventSource } from '@microsoft/fetch-event-source';
fetchEventSource('https://example.com/sse-endpoint', {
method: 'GET',
headers: {
'Content-Type': 'text/event-stream',
},
onopen: async (response) => {
if (response.ok) {
console.log('Connection opened');
} else {
console.error('Failed to open connection');
throw new Error('Failed to open connection');
}
},
onmessage: (event) => {
console.log('New message:', event.data);
// 处理接收到的消息
},
onclose: () => {
console.log('Connection closed');
},
onerror: (err) => {
console.error('Error:', err);
},
});
1. 导入库
import { fetchEventSource } from '@microsoft/fetch-event-source';
2. 调用 fetchEventSource
fetchEventSource('https://example.com/sse-endpoint', {
method: 'GET',
headers: {
'Content-Type': 'text/event-stream',
},
// 其他回调函数
});
- URL:
'https://example.com/sse-endpoint'
是服务器端点的 URL,用于接收 SSE 事件。 - method:
'GET'
是请求方法,SSE 通常使用 GET 请求。 - headers: 设置请求头,
'Content-Type': 'text/event-stream'
表示请求的内容类型为 SSE。
3.回调函数
onopen: async (response) => {
if (response.ok) {
console.log('Connection opened');
} else {
console.error('Failed to open connection');
throw new Error('Failed to open connection');
}
},
- 解释: 当连接成功打开时调用。
response.ok
表示连接是否成功。 - 处理: 如果连接成功,可以执行一些初始化操作;如果失败,可以记录错误并抛出异常。
onclose:
onclose: () => {
console.log('Connection closed');
},
当连接关闭时调用。
通过设置不同的回调函数,可以处理连接打开、消息接收、连接关闭和错误等事件。