Using Nginx as proxy for Node.js' Express and Socket.io

Viewed 81

I want to run an express server and a socket.io server on an node.js instance which are reachable through nginx. If possible, I would favor to run them both on the same port, but I did not reach that goal either.

I can reach the webserver locally and from extern. I can only reach the socket server locally.

When I call the page, my browsers log shows the following error:

GET https://example.com/socket.io/?EIO=3&transport=polling&t=O6qCW5Y
400 Bad Request

So I think the problem lies somewhere in the nginx config.

My app.js code for the socket.io server:

const http = require('http').createServer();
const io = require('socket.io')(http);

http.listen(3001, () => {
    console.log('Socket-Server listening on port: 3001');
});

io.on('connection', (socket) => {
    ...
});

My code for the client:

window.onload = function() {
    const socket = io.connect('https://box-api.com/');

    socket.on('connect', () => {
        ...
    }
}

My nginx config:

server {
    server_name example.com;

    root /nodejs/example.com;
    include static_files.conf;

    index app.js;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
    }
    location /socket.io {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;

        proxy_pass http://127.0.0.1:3001;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # Certbot stuff
    ...
}
0 Answers
Related