express application server. listen to all interfaces instead of only localhost

I am very new to this business and trying to make some kind of express application

var express = require('express'); var app = express(); app.listen(3000, function(err) { if(err){ console.log(err); } else { console.log("listen:3000"); } }); //something useful app.get('*', function(req, res) { res.status(200).send('ok') }); 

When I start the server with the command:

 node server.js 

everything goes well

I see on the console

 listen:3000 

and when i try

 curl http://localhost:3000 

I see "good."

When i try

 telnet localhost 

I see

 Trying 127.0.0.1... Connected to localhost. Escape character is '^]' 

but when i try

 netstat -na | grep :3000 

I see

 tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN 

The question is, why is it listening on all interfaces, not just localhost?

Linux mint 17 OS without any whistles.

+22
source share
3 answers

If you use do not specify a host when calling app.listen , the server will work on all available interfaces ( 0.0.0.0 )

You can bind an IP address using the following code

 app.listen(3000, '127.0.0.1'); 
+53
source

From the documentation : app.listen(port, [hostname], [backlog], [callback])

Binds and listens for connections on the specified host and port. This method is identical to http.Server.listen () nodes.

 var express = require('express'); var app = express(); app.listen(3000, '0.0.0.0'); 
+19
source

document: app.listen([port[, host[, backlog]]][, callback])

Example:

 const express = require('express'); const app = express(); app.listen('9000','0.0.0.0',()=>{ console.log("server is listening on 9000 port"); }) 

Note: 0.0.0.0 will be provided as a host for access from the external interface.

0
source

Source: https://habr.com/ru/post/1236949/


All Articles