Node.JS .listen(port, 'hostname') does not work

时间:2018-12-03 13:13:48

标签: javascript node.js server hostname listen

at the moment I try to spin up a node.js server and I do want to understand the arguments of server.listen.

server.listen(port, hostname, backlog, callback);

Question: as far as I understand this the 2. 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)

3 个答案:

答案 0 :(得分:2)

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.

答案 1 :(得分:1)

You are not allowed to give any random string as host argument. The server tries to bind itself to the provided hostname. So your hostname should either be your ip or a reachable hostname from the dns.

If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.

答案 2 :(得分:0)

我遇到了类似的问题,因为路由器或代理修改了请求的主机名...结果是Intranet和Extranet客户端的两个不同名称。

我的解决方案是将主机名设置为空

server.listen(7000, "")