[英]Socket io not connected after deploy to ubuntu (nginx, nodejs, reactjs)
我有 MERN 应用程序,使用 express 构建 api,使用 reactjs 构建客户端。
在我的本地计算机(Windows)中,客户端可以连接到套接字服务器。 onConnection 事件被触发。
1. 本地计算机 (Windows)
客户端:
socket.on('connect', () => {
console.log('connected to the socket server');
}) // triggered and i can see the console.log in broser console
服务器端:
io.on('connection', () => {
console.log('client connected to the socket server');
}) // triggered and i can see the console.log in terminal
2. VPS (Ubuntu 20, Nginx)
当我将服务器和客户端部署到 vps 时,套接字无法连接。 未触发连接事件。
但是客户端是触发connect_error事件:
socket.on("connect_error", (error) => {
console.log('socket connection error:', error.message) // socket connection error: server error
}); // this event is triggered
这是我的代码:
服务器端:
const server = app.listen(3000)
const io = socketio(server)
客户端:
const socket = io("http://103.150.60.132/api")
NGINX 配置:
server {
listen 80;
location / {
root /var/www/bacotin/client; //reactjs build location
index index.html index.htm;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://103.150.60.132:3000; // express api
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~* \.io {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy false;
proxy_pass http://localhost:3000;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
更新:问题解决了,现在socket客户端可以连接到socket服务器了。
只需修改客户端代码:
由此:
const socket = io("http://103.150.60.132/api")
对此:
const socket = io("http://103.150.60.132")
但为什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.