I don't have to specify a port for heroku for

2019-08-15 03:35发布

问题:

I've successfully made a test chat app and I've gotten a node js server with socket.io running on heroku. On my local computer I have to specify the port number of localhost on the client side to the port that the server has set up. However, when I run my server code on heroku. Removing the server

I'm using the process.env.PORT variable since heroku sets that up:

var port = process.env.PORT || 3000;
http.listen(port, function(){
  console.log('listening on *:' + port);
});

Naturally I find the port number that the app is running on place it in the url

var socket = io('https://xxxx.herokuapp.com:1111');

However this gives me an "net::ERR_CONNECTION_REFUSED".

I got it to work by removing the port nubmer after the url (in this example :1111). I'm wondering why this is working since most of the tutorials and articles online have it specifying the port and why my local computer needs the port to work as well.

回答1:

When you connect to your https://xxxx.herokuapp.com subdomain on heroku on port 443 (which is the port that is used for an https connection when no port is specified), Heroku is probably using a proxy or router to route that incoming connection to the particular port that your node.js server is listening to. In the Heroku infrastructure, they know what actual internal host your server is running on and what actual port number it is running on so they can map a default port request on your subdomain to the actual port/host.

This is done so that browsers can connect to your subdomain directly on the default port without having to know the particulars of your node server installation and so that Heroku can auto-manage your server and likely share hardware with other customers. You are each running on a different port, but sharing the same machine. The ports are managed entirely by Heroku and this is one way that they are able to put multiple customers on the same hardware without each having to specify a custom port in the browser URL (which would be a non-starter for most customers).

So, Heroku is hosting some sort of proxy for your sub-domain that is listening to the default https port. Thus, you don't have to specify the port in the URL. Internally, they route that connection to your actual port on your actual server.

When running on your desktop, there is no such proxy to do this for you so you have to make sure client and server port numbers match.