Younes Mgharfaoui Younes Mgharfaoui - 3 months ago 7
Node.js Question

Running a simple script on a web server using NodeJS

I'm trying to make a simple JS script run on my web server using NodeJS :

var http = require('http');
var server = http.createServer(function(req,res) {
res.writeHead(200,{"Content-Type":"text/plain"});
res.end("Hello World!");
});
server.listen(8000);

console.log('Server running');


Output when I run this on local :

curl http://127.0.0.1:8000
Hello World!


However, when I try to curl onto my web server it timeout.
I don't know if it's important or not but I have apache2 installed on the web server. Any help would be very much appreciated.

Answer

You can't access node.js from outside because it is listening on localhost IP i.e 127.0.0.1. You need to configure node.js to listen on 0.0.0.0 so it will be able to accept connections on all the IPs of your machine. Try this:

server.listen(8000, "0.0.0.0");

If it still doesn't work and you are using iptables you may have to open port 8000. Try this:

iptables -I INPUT -p tcp --dport 8000 -j ACCEPT
Comments