express app server . listen all intefaces instead

2019-04-03 23:16发布

问题:

I'm very new for this stuff, and trying to make some express app

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 fine.

I see on the console

listen:3000

and when I try

curl http://localhost:3000

I see 'ok'.

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 does it listen all interfaces instead of only localhost?

The OS is linux mint 17 without any whistles.

回答1:

If you use don't specify host while calling app.listen, server will run on all interfaces available(0.0.0.0)

You can bind the IP address using the following code

app.listen(3000, '127.0.0.1');


回答2:

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 Node’s http.Server.listen().

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