【发布时间】:2021-12-27 06:54:06
【问题描述】:
我有 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";
}
}
【问题讨论】:
标签: node.js nginx socket.io ubuntu-20.04