English · 中文
Using the Fetch API to request an SSE (Server-Sent Events) endpoint. It is a refactoring of @microsoft/fetch-event-source
, with a more concise code implementation, and it supports use in both Node.js and browser environments.
npm install @sentool/fetch-event-source
import { fetchEventSource } from '@sentool/fetch-event-source';
await fetchEventSource('/api/sse', {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer <token>",
},
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.
<script src="https://unpkg.com/@sentool/fetch-event-source/dist/index.min.js"></script>
<script type="module">
const { fetchEventSource } = FetchEventSource;
fetchEventSource(url, options);
</script>
You can abort the request at any time within any event, for example:
const eventSource = await fetchEventSource(url, options);
// Assume the request is aborted after 3 seconds
setTimeout(() => {
eventSource.abort();
}, 3000);
In addition to the options available 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. |
parseJson |
boolean | Whether to parse the response as JSON. Defaults to true . |
MIT © sentool