参数说明
参数名 | 描述 |
---|---|
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>