我有一台Nginx托管的Ubuntu(https)服务器,它带有运行HTTP服务器的NodeJS程序。 Nodejs http服务器正在侦听端口4001上的socketIO连接。我已经使用Nginx路由/代理了传入请求,以指向该NodeJS服务器。
当将socketio-client与React一起使用时,我可以使用localhost:4001作为我计算机上的连接URL,但是当我将NodeJS和React客户端放在Nginx上时,我无法正确连接。
我曾尝试调整许多事情,但是我现在遇到的错误是React控制台尝试连接时出现“无效的namspace”。我在NodeJS控制台上看到了初始连接。
我的问题是,我的设置哪里出错了?我将在相关代码块下方发布:
Ngnix:
server {
root /var/www/example.com/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
location /socket.io {
proxy_pass http://localhost:4001;
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;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 404; # managed by Certbot
}
反应:
componentDidMount() {
const url = `https://example.com/socket.io`;
this.socket = io.connect(url, {
transports: ['websocket'],
rejectUnauthorized: false,
secure: true
});
this.socket.on("connecting", (data) => {
console.log(data)
});
this.socket.on("connect", (data) => {
console.log('connected')
});
this.socket.on("disconnect", (data) => {
console.log("disconnect", data)
});
this.socket.on("message", (payload) => {
//...
});
this.socket.on("data", (payload) => { ... }
//...
});
this.socket.on("error", (data) => console.log("error", data));
}
NodeJS:
var httpServer = require("http").createServer()
var ioServer = require("socket.io")
var options = {
pingTimeout: 1000000,
pingInterval: 1000
};
var io = new ioServer()
io.attach(httpServer, options)
httpServer.listen(4001)
console.log(`Websocket server started on port: ${4001}...`);
io.on("connection", function connection(client) {
// ...
}