React中EventSource无法接收服务器实时数据的问题排查
问题排查与解决方案
核心问题分析
你的Node.js服务端虽定时调用res.write发送数据,但未主动刷新响应缓冲区,导致数据滞留在内核缓冲区无法送达客户端;同时SSE消息格式存在小瑕疵,可能影响客户端解析逻辑。
修复步骤
1. 修正服务端SSE逻辑
修改Node.js代码,规范消息格式并强制刷新缓冲区:
quizRoute.get("/realtime-questions", (req, res) => { console.log(`request made to realtime-questions`); res.writeHead(200, { "Connection": "keep-alive", "Content-Type": "text/event-stream", "Cache-Control": "no-cache", 'Access-Control-Allow-Origin': '*', "Transfer-Encoding": "chunked" // 启用分块传输,确保数据实时推送 }); // 发送初始连接确认消息 res.write('event: message\n'); res.write('data: connection established\n'); res.write('\n\n'); res.flush(); // 强制刷新缓冲区,立即发送数据 setInterval(() => { console.log('sending data to client'); res.write('event: message\n'); res.write(`data: some data\n`); // 确保data行末尾带换行符 res.write("\n\n"); res.flush(); // 关键:每次发送后刷新缓冲区 }, 10000); });
2. 客户端添加调试监听
在React代码中补充错误与关闭事件监听,方便排查连接异常:
useEffect(() => { fetchQuestion(); const eventSource = new EventSource(`${BaseURL}quiz/realtime-questions`); eventSource.onmessage = (e) => { console.log(`got this data ${e.data}`); updateQuestion(e.data) }; // 监听连接错误 eventSource.onerror = (err) => { console.error('EventSource error:', err); eventSource.close(); }; // 监听连接关闭 eventSource.onclose = () => { console.log('EventSource connection closed'); }; return () => { eventSource.close(); }; }, []);
3. 额外检查项
- 确认
BaseURL拼接后路径正确,避免出现//quiz/realtime-questions这类错误格式 - 打开浏览器控制台Network面板,查看SSE请求的响应内容,验证数据是否实际到达客户端
- 生产环境部署时,确保反向代理(如Nginx)禁用SSE请求的缓存与压缩,保持长连接
内容的提问来源于stack exchange,提问作者Дейвид Аптикадир
相关产品推荐
相关产品推荐

