我有MERN应用程序,api构建与快递和客户端构建与reactjs。
在本地计算机(windows)中,客户端可以连接到套接字服务器。触发onConnection事件。
1.本地计算机()
客户端:
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 (Ubuntu20,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 Config:
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";
}
}
发布于 2021-11-16 08:28:05
更新:问题解决了,现在套接字客户端可以连接到套接字服务器。
只需修改客户端代码:
由此:
const socket = io("http://103.150.60.132/api")
对此:
const socket = io("http://103.150.60.132")
但是为什么呢?
https://stackoverflow.com/questions/69985027
复制相似问题