插件@microsoft/fetch-event-source
时间: 2025-06-04 07:24:24 浏览: 72
### 关于插件 @microsoft/fetch-event-server 的使用方法
`@microsoft/fetch-event-source` 是一个用于实现服务器发送事件(Server-Sent Events, SSE)的库,它提供了类似于 Fetch API 的接口来处理 SSE。以下是该插件的基本使用方法和相关信息[^2]。
#### 1. 安装插件
在使用 `@microsoft/fetch-event-source` 前,需要通过 npm 或 yarn 安装该插件:
```bash
npm install @microsoft/fetch-event-source
```
或者使用 yarn:
```bash
yarn add @microsoft/fetch-event-source
```
#### 2. 基本使用示例
以下是一个基本的代码示例,展示如何使用 `@microsoft/fetch-event-source` 来连接到 SSE 端点并处理接收到的数据:
```javascript
import { fetchEventSource } from '@microsoft/fetch-event-source';
fetchEventSource('https://example.com/sse-endpoint', {
method: 'GET',
headers: {
'Authorization': 'Bearer your-token-here'
},
onopen(response) {
console.log('Connection opened with status:', response.status);
},
onmessage(msg) {
console.log('Received message:', msg.data);
},
onerror(err) {
console.error('Error occurred:', err);
}
});
```
- **`fetchEventSource`**:这是插件的核心函数,类似于 Fetch API 的 `fetch` 方法。
- **`onopen`**:当连接成功打开时触发。
- **`onmessage`**:每当从服务器接收到新消息时触发。
- **`onerror`**:当发生错误时触发。
#### 3. 高级配置选项
`fetchEventSource` 支持多种配置选项,例如设置重试逻辑、自定义解析器等。以下是一些常用的配置项:
- **`retry`**:指定重试间隔时间(以毫秒为单位)。如果设置为 `false`,则禁用自动重试。
- **`parser`**:自定义消息解析器,用于处理非标准格式的消息。
- **`timeout`**:设置请求超时时间。
示例代码如下:
```javascript
fetchEventSource('https://example.com/sse-endpoint', {
retry: 5000, // 每隔 5 秒重试一次
parser: (event) => JSON.parse(event.data), // 自定义解析器
timeout: 30000 // 超时时间为 30 秒
});
```
#### 4. 处理断开连接
可以通过调用返回的控制器对象的 `abort` 方法来手动断开连接:
```javascript
const controller = fetchEventSource('https://example.com/sse-endpoint', {
onmessage(msg) {
console.log('Message received:', msg.data);
}
});
// 在某个条件下断开连接
setTimeout(() => {
controller.abort();
console.log('Connection aborted.');
}, 60000); // 60 秒后断开连接
```
---
### 注意事项
- 确保服务器端支持 SSE,并且返回的内容类型为 `text/event-stream`[^3]。
- 如果需要跨域访问,请确保服务器端正确配置了 CORS 头部。
- 在生产环境中,建议对重试逻辑进行优化,避免频繁重试导致性能问题。
---
阅读全文
相关推荐



















