简体   繁体   中英

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.

You can't access node.js from outside because it is listening on localhost IP ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM