在生产环境中,通过nginx配置后,前端无法正常接收SSE(Server-Sent Events)消息推送。
后端SSE实现:
SseEmitter实现/resource/sse前端SSE实现:
useEventSource组合式APInginx代理配置:
# SSE专用代理配置(重要:必须放在其他API配置之前)
location ^~ /prod-api/resource/sse {
proxy_pass http://47.121.125.41:8080/resource/sse;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# SSE特殊配置
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
# SSE需要更长的超时时间
proxy_connect_timeout 60s;
proxy_send_timeout 86400s; # 24小时
proxy_read_timeout 86400s; # 24小时
# SSE响应头设置
proxy_set_header Accept "text/event-stream";
proxy_set_header Cache-Control "no-cache";
proxy_set_header Connection "keep-alive";
# CORS处理
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization,clientid';
add_header Access-Control-Allow-Credentials true;
if ($request_method = 'OPTIONS') {
return 204;
}
}
proxy_buffering off:禁用nginx缓冲,确保SSE消息实时传输proxy_cache off:禁用缓存,避免消息被缓存proxy_read_timeout 86400s:设置24小时超时,支持长连接proxy_set_header Connection "":清除Connection头,避免代理问题add_header Access-Control-Allow-Credentials true:支持跨域认证# 推荐配置:通过nginx代理
VITE_APP_BASE_API = '/prod-api'
VITE_APP_SSE = true
VITE_APP_WEBSOCKET = false
# 备选配置:直接访问后端
VITE_APP_BASE_API = 'http://47.121.125.41:8080'
VITE_APP_SSE = true
VITE_APP_WEBSOCKET = false
# 备份原配置
cp /etc/nginx/conf.d/hzdyjsweb.camasort.com.conf /etc/nginx/conf.d/hzdyjsweb.camasort.com.conf.backup
# 更新配置文件
vim /etc/nginx/conf.d/hzdyjsweb.camasort.com.conf
# 测试配置
nginx -t
# 重新加载配置
nginx -s reload
# 进入前端项目目录
cd /path/to/frontend
# 更新环境变量
vim .env.production
# 重新构建
npm run build
# 部署到nginx目录
cp -r dist/* /root/hzdyjsweb9091/dist/
# 重启后端服务(如果需要)
systemctl restart your-backend-service
# 检查nginx状态
systemctl status nginx
# 测试nginx配置
nginx -t
# 查看nginx错误日志
tail -f /var/log/nginx/error.log
tail -f /var/log/nginx/hzdyjsweb.camasort.com.error.log
# 查看nginx访问日志
tail -f /var/log/nginx/hzdyjsweb.camasort.com.access.log
// 检查SSE连接状态
console.log('SSE连接状态:', EventSource.readyState);
// 0: CONNECTING, 1: OPEN, 2: CLOSED
curl -H "Authorization: Bearer YOUR_TOKEN" \
-H "clientid: e5cd7e4891bf95d1d19206ce24a7b32e" \
http://47.121.125.41:8080/resource/sse
curl -H "Authorization: Bearer YOUR_TOKEN" \
-H "clientid: e5cd7e4891bf95d1d19206ce24a7b32e" \
http://hzdyjsweb.camasort.com/prod-api/resource/sse
# 查看应用日志
tail -f /path/to/backend/logs/application.log
# 查看SSE相关日志
grep -i "sse" /path/to/backend/logs/application.log
# 连接Redis
redis-cli
# 检查SSE主题订阅
SUBSCRIBE global:sse
更新时间:2025-01-03
维护人员:系统管理员
文档版本:v1.0