使用
const options {
withCredentials: true, // 默认 false
}
const eventSource = new EventSource(`/api`, options);
eventSource.addEventListener('open', () => {});
eventSource.onmessage = (event) => {}; // 或addEventListener('message',callback)
eventSource.addEventListener('error', (event) => {});
注意:message 为默认事件
后端可配合前端使用自定义事件
后端配置 content-type="text/event-stream"
参考:https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html