I was about teaching my friend an intro to node but then I wonder why this code 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 hosted, it doesn't accessible from public ip (it's still accessible from localhost though) while this code 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 modify the basic code the one from nodejs's homepage so that it become accessible from public ip so I can demonstrate it to my friend in a very basic way. The fresh code generated by express.js worked just fine.
What am I missing here?
Node (or more formally Node. js) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS).
Creating and starting a server is easy with Node. js's built-in http module. and visit http://localhost:3000 in your browser. You should see that our server is running, and you are greeted with the text "Hello, World!" in your browser.
Node. js can't be over client side. It's basically a server that have to started @ one end before it could be used with client conjuction. However it could be restarted or make to run continuously using nodemon, forever but for first also it had to be started manually.
As per the server.listen
docs,
Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).
To make it accept connections from all ips (0.0.0.0
), change it to read like this
}).listen(80); // No explicit ip, defaults to all ips 0.0.0.0
console.log('Server running in port 80');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With