Node.JS Not working on the internet
Asked Answered
T

3

11

i have the basic webserver hello world app for nodejs on windows and it works on localhost. But when i test it from the internet it cannot connect. I set up port forwarding in my netgear router. Am i missing a step here to make my nodejs server visible to the outside world?

Thanks.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Twodimensional answered 26/8, 2011 at 16:38 Comment(2)
It would help if you show us the code you are using.Epact
It's just the hello world web server on nodejs website.Twodimensional
S
18

Make sure you listen on 0.0.0.0 instead of 127.0.0.1

127.0.0.1 is a private network visible only to your computer. 0.0.0.0listens to all interfaces, including both the private and public (as public as it can be behind a NAT).

Selfsupporting answered 26/8, 2011 at 17:34 Comment(5)
Cool, where did you learn that? Didn't even know 0.0.0.0 was a valid ip.Twodimensional
Picked it up somewhere in Linuxland, probably editing lighttpd configs by hand or something. It's been awhile.Selfsupporting
I have the same problem, I did use 0.0.0.0 but still can't access my server outside.Tenia
@xybrek: create a new question, it's probably a router configuration issue though.Selfsupporting
@insta I just created a new nodejs server using Ubuntu which fixed everything. And did iptablesTenia
P
0

Looks like you're binding the server to IP Address 127.0.0.1 which is localhost. If you want to access it elsewhere you'll need to set it to it's internet IP. Check out whatismyip.com and use that IP instead.

Professionalism answered 26/8, 2011 at 17:36 Comment(2)
This won't work if he's behind a NAT. His internal IP address will (likely) be 192.168.x.x, but his public address will be something entirely different.Selfsupporting
what to do if you're behind a NAT?Belostok
R
0

Just to make sure.

Your code should run like this.

var http = require('http');
const port = 1337;
const host = '0.0.0.0';

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(port, host);
console.log('Server running at http://${host}:${port}');
Relict answered 14/8, 2021 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.