Nginx / MEAN Stack – WebSocket is closed before the connection is established

  angular, nginx, node.js, sockets, ubuntu

First I had some CORS issue with socket.io in productive (have no issue in development).
I fixed that and everything seems to work fine, but now I get this warning WebSocket is closed before the connection is established.

Still cannot exchange any messages.
But it works fine in localhost, so I guess there is some incorrect settings.

I am using the MEAN Stack and Nginx for webserver and use reverse proxy.

Here is my backend setting to connect to socket.io:

const app = express();
const port = process.env.PORT || 3000;
const server = http.createServer(app);

const io = require('socket.io')(server, {
   path: '/ws/',
   serveClient: false,
   cors: {
      origin: 'http://141.62.65.110',
      methods: ["GET", "POST"],
      credentials: true  
   }
});

On my client in Angular, this is my connection:

private socket = io('http://141.62.65.110:3000/', { transports: ["websocket"], path: '/ws/', secure: false });

Finally my Nginx config:

server {
    listen 80;

    server_name http://travelinked.vm.mi.hdm-stuttgart.de;

    location / {
        root /var/www/html;
        try_files $uri $uri/ /index.html;
    }    

    location /ws/ {
        rewrite /ws/(.*) /$1  break;
        proxy_pass http://141.62.65.110:3000;
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    } 

    location /api/ {
        rewrite /api/(.*) /$1  break;
        proxy_pass http://141.62.65.110:3000;
        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;
    }
   
}

So CORS is no problem anymore, just the problem that WebSocket is closed before the connection is established.

Any settings missing?

Thank you in advance.

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.