I am trying to spin up a node.js server and I want to understand the arguments of server.listen
:
server.listen(port, hostname, backlog, callback);
As far as I understand this, the 2nd argument of listen
should be a hostname. The result should be, that I am able to reach the server over "hostname:7000" but the result is that the script is crashing. Without "hostname" everything works fine. Whats the problem here? What is the usage of "hostname"?
const server = http.createServer(function (req, res) {
console.log(req);
});
server.listen(7000, "bla");
Browser:
bla:7000
doesn't work.
Error:
Error: listen EADDRNOTAVAIL 22.0.0.0:7000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1246:19)
at listen (net.js:1295:10)
at net.js:1405:9
at _combinedTickCallback (internal/process/next_tick.js:77:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
at Module.runMain (module.js:606:11)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
The hostname
argument is used in situations where a server has more than one network interface, and you only want the server to listen on one of those interfaces (as opposed to the default, which is to listen to all interfaces).
For instance, if you want the server to be only accessible by clients running on the server itself, you make it listen on the loopback network interface, which has IP-address "127.0.0.1" or hostname "localhost":
server.listen(7000, "localhost")
server.listen(7000, "127.0.0.1")
It doesn't mean that you can just enter any hostname and magically get the ability to access the server through that hostname, that's not how it works or what it is intended for.