HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
877 stars 142 forks source link

Upgrade connection #167

Open rmamba opened 3 months ago

rmamba commented 3 months ago

I'm having problems with connecting to server that is behind nginx reverse proxy that handles SSL certificates. Back end is unsecured so the upgrade of the connection is not working.

my nginx config for the WebSocket part:

location /ws {
  proxy_pass http://upstreamServer/ws;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $host;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header X-Real-IP $remote_addr;
  proxy_http_version 1.1;
  proxy_read_timeout 86400;
}

NodeJS code:

app.ws('/ws', function (ws, req) {
    console.log('Client connected');

    ws.on('close', function close() {
        console.log('Client disconnected...');
    });

    ws.on('upgrade', (request, socket, head) => {
        console.log('Upgrade connection');
        ws.handleUpgrade(request, socket, head, (websocket) => {
            console.log('Connection upgraded');
            ws.emit("connection", websocket, request);
        });
    });
});

I see Client connected and then righjt away Client disconnected messages in log file.