简体   繁体   中英

Running socket.io behind nginx at a sublocation

I am trying to run an express-socket.io-angular.js Application on a raspberry my at my home.

Express and socket.io are running on port 3001. Accessing the Application at http://[IP]:3001 works fine. I would like to access the application at http://[IP]/ttt .

I configured nginx like this:

location /ttt/ {
    proxy_pass http://localhost:3001/;
}

On the server i run these lines of code:

var express = require('express');
var app = express();
var http = require('http').Server(app);

...

app.use(express.static(__dirname + '/public'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));

...

var io = require('socket.io')(http, {path: '/ttt/socket.io'});

...

http.listen(3001, function () {
    console.log('Listening on port 3001');
});

and at the client I include socket.io like this:

<script src="socket.io/socket.io.js"></script>

and connect like this:

socket: Socket = io.connect({path: "/ttt/socket.io"});

The problem:

I get all resources (html, css, js incl. socket.io.js), but in the browserlog i get error messages, that it was not able to get http://[IP]/socket.io/?EIO=3&transport=polling&t=LNGvDUd where t changes frequently.

It reports status 404, it's obvious, because nginx doesn't respond at /socket.io.

Thanks in advance!


Combined results with jfriend00:

The working setup looks like this:

nginx (found more details about the correct configuration here ):

location /ttt/ {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://localhost:3001/;
    }

Express:

var io = require('socket.io')(http);

Client (Typescript):

socket: Socket = io({path: "/ttt/socket.io"});

If I understand your proxy configuration correctly, it is going to strip off the /ttt from the path before forwarding on to port 3001. As such, your socket.io initialization is not correct on the server.

Change this:

var io = require('socket.io')(http, {path: '/ttt/socket.io'});

to this:

var io = require('socket.io')(http);

EDIT:

And, make sure that your client file that's loading into the browser is actually the latest edited client file. You can check it with View/Source in the browser to see exactly what file you're running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM