Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - express app server . listen all interfaces instead of localhost only

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

You can bind the IP address using the following code

app.listen(3000, '127.0.0.1');

If you want to run server in all interface use the following code

app.listen(3000, '0.0.0.0');

or

app.listen(3000)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...