express app server . listen all interfaces instead of localhost only

Javascriptnode.jsExpressMean

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

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');

Solution 3 - Javascript

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 to be given as host in order to access from outside interface

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPavel LView Question on Stackoverflow
Solution 1 - JavascriptVishnuView Answer on Stackoverflow
Solution 2 - JavascriptJulien Le CoupanecView Answer on Stackoverflow
Solution 3 - JavascriptThavaprakash SwaminathanView Answer on Stackoverflow