我从nginx反向代理后面的 http://socket.io/#how-to-use 设置了第一个 socket.io 示例"与Node HTTP服务器一起使用"。 只要我将其保留为 http,就可以按预期工作。 如果我通过引入nginx重写规则将http重写为https(终止于nginx(,我无法使其正常工作。
客户端控制台.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>
服务器.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);
});
});
您正在通过HTTPS发送不安全的内容。 试试这些:
索引.html
var socket = io.connect('https://'+window.location.host+':8001'); //added https...
服务器.js:
var app = require('https').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
var options = {
key: fs.readFileSync('crts/ssl.key'), //the route to your certs.
cert: fs.readFileSync('crts/ssl.cert'),
ca: fs.readFileSync('crts/ssl.ca')
};
https.createServer(options, app).listen(8001); //https server
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);
});
});