# fetch-event-source
**Repository Path**: zaoangod/fetch-event-source
## Basic Information
- **Project Name**: fetch-event-source
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: main
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2024-10-12
- **Last Updated**: 2024-11-20
## Categories & Tags
**Categories**: Uncategorized
**Tags**: SSE, fetch, fetch-sse
## README
# fetch-event-source
## Usage
```js
import {FetchEventSource} from 'fetch-event-source';
await new FetchEventSource('/api/sse', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
// ...
},
body: JSON.stringify({
input: ''
}),
onOpen(response) {
console.log('Request has been opened.');
},
onMessage(event) {
console.log(event);
},
onError(error) {
console.error(error);
},
done() {
console.log('Stream has completed.');
}
});
```
You can also use a CDN to include it.
```html
```
You can abort the request at any time within any event, for example:
```js
const eventSource = new FetchEventSource(url, option);
setTimeout(() => {
eventSource.abort();
}, 3000);
```
### Option
In addition to [the option available](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) in the Fetch API, the following extra options have been added:
| option | type | description |
|-------------|:---------|:-----------------------------------------------------|
| `onOpen` | function | Call when the request has been opened. |
| `onMessage` | function | Call when data is received function an event source. |
| `onError` | function | Call when an error occurs. |
| `done` | function | Call when the stream has completed. |