我在 nginx 反向代理后面从http://socket.io/#how-to-use设置了第一个 socket.io 示例“使用 Node HTTP 服务器” 。只要我将其保留为 http,它就可以按预期工作。如果我通过引入 nginx 重写规则将 http 重写为 https(终止于 nginx),我将无法使其正常工作。
客户端 console.log 显示:
SecurityError: The operation is insecure. socket.io.js (line 2371)
this.websocket = new Socket(this.prepareUrl() + query);
TypeError: this.websocket is undefined socket.io.js (line 2438)
this.websocket.close();
我对nodejs和nginx都很陌生,所以我很可能会犯一些基本错误,但是经过数小时的试验和谷歌搜索后,我仍然无法让它完全正常工作。
Nginx (v1.4.1) 配置文件:
upstream dev {
server 127.0.0.1:8001;
}
server {
# Listen on 80 and 443
listen 80;
listen 443 ssl;
server_name _;
ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location /dev/ {
if ($ssl_protocol = "") {
rewrite ^ https://$host$request_uri? permanent;
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://dev/;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
索引.html:
<script src="./socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://'+window.location.host+':8001');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
server.js:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8001);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});