我在使用nginx代理时,websocket连接遇到了问题。如果我将端口添加到use effect中,则可以正确连接。
以下是react的代码:
useEffect(() => {
console.log('web socket')
const socket = new WebSocket(`ws://${window.location.hostname}/websocket`);
socket.onopen = () => socket.send('Connected to React')
setSocketIo(socket)
}, [])
这是nginx配置片段。
location /websocket/ {
proxy_pass http://localhost:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
这是我在控制台中收到的错误信息。
WebSocket 连接到 'ws://localhost/websocket' 失败:
从 nginx 日志中看到的错误信息:
2022/04/13 13:23:42 [error] 16848#8212: *1499 connect() failed (10061: No connection could be made because the target machine actively refused it) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET /socket.io/?EIO=4&transport=polling&t=O0ac97J HTTP/1.1", upstream: "http://[::1]:3000/socket.io/?EIO=4&transport=polling&t=O0ac97J", host: "localhost", referrer: "http://localhost/guac"
它会自动将 socket.io 添加到主机名的末尾吗?
WebSocket连接到'ws://localhost/websocket'失败:
来自nginx日志的错误信息2022/04/13 13:23:42 [error] 16848#8212: *1499 connect() failed (10061: No connection could be made because the target machine actively refused it) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET /socket.io/?EIO=4&transport=polling&t=O0ac97J HTTP/1.1", upstream: "http://[::1]:3000/socket.io/?EIO=4&transport=polling&t=O0ac97J", host: "localhost", referrer: "http://localhost/guac"
- Vinh Taerror.log
中看到GET /socket.io/...
,检查你的代码(请求方) - user973254