Hello. I worked with socket.io only locally, so I pointed out on this part of the calient:

<script src="/socket.io/socket.io.js"></script> <script> const socket = io('http://localhost:4000/'); </script> 

now I load the application to Now and my socket cannot connect to the server, because the server is no longer local. On the server side, I specify:

 io = require('socket.io')(http); http.listen(process.env.PORT || 4000, function() { console.log('server is working! '+ this.address().port); }); 

and here I am faced with the problem that I don’t know how to transfer process.env.PORT from the server to the client side so that socket.io can work

I tried to do this: on the server:

 const port = process.env.PORT || 4000; app.get('/setHost', function(req, res){ res.statusCode = 200; res.end(''+ port); }); 

on the client:

 var xhr = new XMLHttpRequest(), port; xhr.open('GET', 'setHost', false); xhr.send(); if (xhr.status != 200) { alert( xhr.status + ': ' + xhr.statusText ); } else { alert( xhr.responseText ); port = xhr.responseText; } const socket = io(port); 

but even when I download the application to the Internet, I get 4000 in the alert. What could be wrong?

1 answer 1

In the listen block, add this.address().port app.locals.port and pass the template to the template engine and <script>window.PORT = {port};</script> . Further, on the front, consider the port to a variable in your class and after that, do not forget to remove the PORT variable from global - this is mandatory.