JavaScript 中使用 EventSource 实现 SSE 推送,需创建实例监听 message 或自定义事件,服务端返回 text/event-stream 并保持连接,支持自动重连、事件 ID 和断线恢复,认证推荐用 Cookie 或 URL 传 token。

JavaScript 中使用 Server-Sent Events(SSE)接收服务器推送,核心是创建 EventSource 实例并监听事件。它比 WebSocket 更轻量,专为单向(服务端 → 浏览器)实时数据设计,天然支持自动重连、事件 ID 管理和断线恢复。
创建 EventSource 并监听消息
最基础的用法是传入服务端 SSE 接口地址,监听 message 事件:
const eventSource = new EventSource('/api/notifications');
eventSource.onmessage = function (event) {
console.log('收到普通消息:', event.data);
};
eventSource.onerror = function (err) {
console.error('SSE 连接出错:', err);
};
注意:event.data 总是字符串,如需对象需手动 JSON.parse();服务端响应必须设置 Content-Type: text/event-stream,且保持连接不关闭。
监听自定义事件类型
服务端可通过 event: xxx 声明事件名,前端用 addEventListener 分别处理:
立即学习“Java免费学习笔记(深入)”;
- 服务端发送(每条以空行分隔):
event: user-updated
data: {"id":123,"name":"Alice"}
event: order-paid
data: {"order_id":"ORD-789","amount":299.99}
- 前端监听:
eventSource.addEventListener('user-updated', (e) => {
const user = JSON.parse(e.data);
updateUserInfo(user);
});
eventSource.addEventListener('order-paid', (e) => {
const order = JSON.parse(e.data);
showPaymentSuccess(order);
});
处理连接状态与重连控制
EventSource 默认在断开时自动重试(通常延迟约 3 秒),可通过服务端 retry: 字段调整,或前端配置:
- 服务端指定重试间隔(单位毫秒):
retry: 5000 data: hello
- 前端手动关闭与重启:
// 关闭连接
eventSource.close();
// 重新连接(例如登录后)
eventSource = new EventSource('/api/stream?token=' + token);
注意:关闭后不会自动重连,需重新实例化;若页面卸载前未 close(),浏览器会自动清理连接。
携带认证信息(如 Token 或 Cookie)
SSE 请求默认携带当前域 Cookie,适合基于 Session 的鉴权;如需 Bearer Token,可借助 withCredentials 和 headers(⚠️但标准 EventSource 构造函数不支持 headers):
- 推荐方式:将 token 放在 URL 查询参数中(确保 HTTPS):
const token = localStorage.getItem('auth_token');
const eventSource = new EventSource(`/api/stream?token=${encodeURIComponent(token)}`);
- 或利用 Cookie + 后端校验(更安全,无需暴露 token 在 URL):
// 前端无需额外操作,只要同域且已登录,Cookie 自动带上
const eventSource = new EventSource('/api/stream');
服务端需设置 CORS 允许凭据:Access-Control-Allow-Origin: https://your-site.com(不能为 *),并返回 Access-Control-Allow-Credentials: true。


















