11

我在 Windows 上有用于 nodejs 的基本 webserver hello world 应用程序,它可以在 localhost 上运行。但是当我从互联网上测试它时,它无法连接。我在我的网件路由器中设置了端口转发。我是否错过了让我的 nodejs 服务器对外界可见的步骤?

谢谢。

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/');
4

3 回答 3

18

确保你听0.0.0.0而不是127.0.0.1

127.0.0.1是仅对您的计算机可见的专用网络。 0.0.0.0侦听所有接口,包括私有和公共(尽可能公共,因为它可以在 NAT 后面)。

于 2011-08-26T17:34:17.323 回答
0

看起来您正在将服务器绑定到127.0.0.1本地主机的 IP 地址。如果你想在其他地方访问它,你需要将它设置为它的互联网 IP。查看 whatismyip.com 并改用该 IP。

于 2011-08-26T17:36:16.747 回答
0

只想确认一下。

你的代码应该像这样运行。

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}');
于 2021-08-14T14:21:45.227 回答