Why is Node.js app available only with 127.0.0.1/localhost?

I taught my friend an introduction to node, but then I wonder why this code is from nodejs.org:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(80, '127.0.0.1');
console.log('Server running at http://127.0.0.1:80/');

when placed, it is not accessible from the public ip (it is still accessible from localhost) while this code is from express.js:

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 80);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

does. Please help me change the base code on the nodejs page so that it becomes accessible from the public ip, so I can demonstrate it to my friend in a very simple way. Fresh code generated by express.js worked fine.

What am I missing here?

+4
source share
2 answers

According to the server.listendocs,

. , , IPv4 (INADDR_ANY).

ips (0.0.0.0), ,

}).listen(80); // No explicit ip, defaults to all ips 0.0.0.0
console.log('Server running in port 80');
+12

127.0.0.1 -

localhost - ( ), (./etc/hosts)

0.0.0.0 - , , ( , )

, , node require ('http'). createServer(). listen() 0.0.0.0 localhost 127.0.0.1

+4

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


All Articles