React WebSocket连接失败排查:Nginx或前端代码疑问
WebSocket连接失败排查:Nginx、前端还是配置问题?
错误信息
WebSocketClient.js:16 WebSocket connection to 'ws://12.345.678.90:5000/ws' failed: WebSocketClient @ WebSocketClient.js:16 initSocket @ socket.js:24 (anonymous) @ socket.js:48
问题背景
这是Nginx错误还是JavaScript错误?找了相关帖子但没找到有效解决方案。
服务器运行在Lightsail实例的Ubuntu系统上,采用Python后端+React(js/tsx)前端架构。
当前Nginx配置
location /api/ { proxy_pass http://localhost:8000/; proxy_set_header Host $http_host; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } location / { proxy_pass http://localhost:5000/; proxy_set_header Host $http_host; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } location /dashboard/ { rewrite ^/dashboard/(.*) /$1 break; proxy_set_header Host $http_host; proxy_pass http://grafana; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } # Proxy Grafana Live WebSocket connections. location /dashboard/api/live/ { rewrite ^/dashboard/(.*) /$1 break; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $http_host; proxy_pass http://grafana; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } # Proxy for websocket server test location /ws { proxy_pass http://localhost:5000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $http_host; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } } }
疑问
这是我的.tsx代码存在问题吗?
问题定位与排查方案
这个错误是前端JS层面的连接失败提示,但根源可能在Nginx配置、后端服务或网络,不能直接定性。以下是具体排查方向:
1. Nginx配置问题
- 路径拼接错误:
/wslocation的proxy_pass http://localhost:5000末尾缺少/,会导致请求被转发到http://localhost:5000ws(而非预期的/ws路径),应改为proxy_pass http://localhost:5000/; - 缺失变量定义:检查Nginx的http块是否定义了
$connection_upgrade变量,这是WebSocket代理必须的,添加代码:map $http_upgrade $connection_upgrade { default upgrade; '' close; } - 查看日志:检查
/var/log/nginx/error.log和access.log,看反向代理时是否有报错。
2. 前端代码问题
- 连接地址错误:前端直接访问
ws://12.345.678.90:5000/ws可能绕过了Nginx的认证,且5000端口可能未对外暴露。应改为通过Nginx代理的地址,比如:new WebSocket(`${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/ws`) - 查看详细错误:打开浏览器控制台Network面板,找到WebSocket请求,查看具体状态码(403是认证失败、404是路径不存在、502是后端无响应)。
3. 后端与网络问题
- 验证后端服务:在服务器本地执行
curl http://localhost:5000/ws,确认后端WebSocket服务是否正常响应。 - 防火墙检查:Lightsail实例只需开放80/443端口(Nginx入口),5000端口仅需本地访问,无需对外开放。
快速验证步骤
- 修正Nginx的
/ws代理路径,添加$connection_upgrade配置,重启Nginx:sudo systemctl restart nginx - 修改前端WebSocket连接地址为当前域名的
/ws路径 - 查看浏览器Network面板的请求详情,根据错误码进一步处理
内容的提问来源于stack exchange,提问作者jd_h2003
相关产品推荐
相关产品推荐

