带有Nginx + NodeJS跨域请求的Socket.io仅部分起作用

时间:2018-12-07 15:24:16

标签: javascript node.js nginx socket.io

我有一个具有 nginx nodejs 服务器的服务器系统。根据子域,它将通过proxy_pass被“转发”到正确的NodeJS应用。

现在我想从另一个来源使用Socket.io。 联接起作用。 (触发了加入事件) 但是当我发出声音或听不见的声音时。

我没有任何异常,但是事件没有被触发。

后端代码:

io.set('origins', '*:*');

io.on('connection', function (client) {
    console.log(client.id + " joined!"); //event fired

    client.on('helloworld', function () {
        console.log(client.id + " said hello!"); //event not fired
    });
}

前端代码:

var io = io("https://subdomain.example.com");
io.emit("helloworld");

Nginx脚本:

server{
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/subdomain.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/subdomain.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_name subdomain.example.com;

    location / {
        limit_conn addr 10;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass    http://127.0.0.1:7005/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Access-Control-Allow-Origin "*";
        proxy_set_header Access-Control-Allow-Headers "origin, x-requested-with, content-type";
        proxy_set_header Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS";
    }
}

我尝试过的可能性:

Socket.io + NodeJS + Nginx + SSL

Cross-domain connection in Socket.IO

Socket.io + Node.js Cross-Origin Request Blocked

2 个答案:

答案 0 :(得分:1)

我发现了我的错误。这比我想的要简单得多。问题是 NodeJS后端代码我只在“ /”命名空间上监听了

使用websocket搜索错误的一个好技巧是在Google Chrome浏览器中打开 Dev工具->网络->?EIO = 3&transport = websocket&sid = qdozsXxTmOHh0JcJAAAJ->框架

在这里您可以看到网络套接字“发送”和“接收”的数据。

Dev Tools -> Network -> ?EIO=3&transport=websocket&sid=qdozsXxTmOHh0JcJAAAJ -> Frames

答案 1 :(得分:0)

尝试两件事:

  1. 在前端代码中,尝试仅在连接为 成功
  2. 检查nginx日志中是否有错误或连接断开