eventsource 默认不支持直接传入认证凭据,但可通过 withcredentials 配合服务端 cors 配置实现 cookie 认证;若需传递 bearer token,则必须使用 fetch + readablestream 手动解析 sse 流,并自行处理重连、错误及 token 刷新。

EventSource 默认不支持直接传入认证凭据(如 Bearer Token 或 Cookie),但可以通过 withCredentials 配合服务端设置,或使用 fetch + ReadableStream 替代方案实现带认证的 SSE 连接。
启用 withCredentials 并配合服务端 CORS 配置
这是最常用、兼容性最好的方式。EventSource 支持 withCredentials: true 选项(需通过构造函数第二个参数传入),但前提是服务端必须明确允许凭据且不能使用通配符 * 设置 Access-Control-Allow-Origin。
- 前端代码示例:
const eventSource = new EventSource('/api/stream', {
withCredentials: true
});
- 服务端响应头必须包含(以 Express 为例):
res.set({
'Access-Control-Allow-Origin': 'https://your-frontend-domain.com', // 不能是 *
'Access-Control-Allow-Credentials': 'true',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
- 此时浏览器会自动携带 Cookie(若已登录)或 TLS 客户端证书(如配置了);Token 无法通过 EventSource 自动注入,需依赖 Cookie 或服务端 Session 关联
用 fetch + ReadableStream 手动解析 SSE(支持自定义 Authorization 头)
当需要显式传递 Bearer Token 等 Header 时,EventSource 无能为力,必须改用 fetch 获取流式响应,并用 ReadableStream 解析事件格式。
- 关键点:fetch 支持
headers,且响应体可读取为流;SSE 格式简单(data: ...\n\n或event: ...\ndata: ...\n\n) - 基础实现片段:
const controller = new AbortController();
const response = await fetch('/api/stream', {
headers: { 'Authorization': 'Bearer abc123' },
signal: controller.signal
});
if (!response.ok) throw new Error('SSE connection failed');
const reader = response.body.getReader();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += new TextDecoder().decode(value);
// 简单按双换行切分事件块
const lines = buffer.split(/\n\n/);
buffer = lines.pop() || ''; // 保留不完整事件
for (const chunk of lines) {
if (!chunk.trim()) continue;
const event = parseSSELine(chunk); // 自定义解析函数
if (event?.type === 'message') console.log(event.data);
}
}
注意重连与错误处理
EventSource 自带重连机制(默认 3s),但 fetch 方案需手动实现;无论哪种方式,都应监听网络异常并提供降级策略。
- EventSource 错误监听:
eventSource.onerror只反映连接失败,不区分具体原因;建议结合onclose和定时检查eventSource.readyState - fetch 方案中,可在
catch或AbortSignal触发后延迟重试,避免高频请求 - 服务端应发送
retry:字段(如retry: 5000),但仅 EventSource 原生识别;fetch 方案需自行解析并应用
Token 过期与刷新逻辑
若使用 Token 认证,需考虑有效期。EventSource 无法动态更新 Header,因此推荐:
- Token 存储在 Cookie 中(HttpOnly + Secure + SameSite=Lax/Strict),由服务端验证,前端只需开启
withCredentials - 若必须用 Header Token,优先选用 fetch 方案,并在每次重连前获取新 Token(例如调用
/auth/refresh) - 避免在 EventSource URL 中拼接 Token(如
?token=xxx),易泄露且不安全
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











