Max Mister
Max Mister

Reputation: 129

Socket.io with Nginx + NodeJS Cross-Origin Request works only partially

I have a server system with a nginx and a nodejs server. Depending on the subdomain, it will be "forwarded" to the correct NodeJS app with proxy_pass.

Now I want to use Socket.io from another origin. The join works. (join event triggered) BUT when I emit something or listen on something it doesn't work.

I don't get any exception, but the events are not triggered.

Backend Code:

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
    });
}

Frontend Code:

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

Nginx Script:

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";
    }
}

Possibilities I tried:

Socket.io + NodeJS + Nginx + SSL

Cross-domain connection in Socket.IO

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

Upvotes: 1

Views: 266

Answers (2)

Max Mister
Max Mister

Reputation: 129

I found my mistake. It was much simpler than I thought. The problem was the NodeJS backend code I only listened on the "/" namespace.

A good tip to search errors with websockets is to open in Google Chrome the Dev Tools -> Network -> ?EIO=3&transport=websocket&sid=qdozsXxTmOHh0JcJAAAJ -> Frames

Here you can see the data which is "sent" and "received" by the websockets.

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

Upvotes: 1

Praveen penumaka
Praveen penumaka

Reputation: 1

Try two things:

  1. In frontend code, Try to emit only after the connection is successful
  2. Check nginx logs for errors or dropping of connections

Upvotes: 0

Related Questions