【问题标题】:Deploying nodejs app on a web server在 Web 服务器上部署 nodejs 应用程序
【发布时间】:2015-07-08 12:37:15
【问题描述】:

我是 NodeJS 和学习新手,我想知道如何使用 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/');

这是代码以 m.js 的形式保存在我的本地机器中,我运行:

$ node m.js

它运行良好,当我在浏览器中以https://127.0.0.1:1337 的身份打开它时

我得到的输出是:

Hello World

我想从远程服务器上做同样的事情,即我有一个域www.example.com,如果我用https://www.example.com:1337 打开它 然后它应该像以前一样显示在我的浏览器屏幕上:

Hello World

但它不起作用。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    @Annanta 127.0.0.1:1337 是本地机器 ip 地址。请删除这个。 请在下面找到示例代码。尝试使用远程服务器 ipaddress 访问它。请注意,远程机器必须安装 node 和 npm。

    var http = require("http");
    
    http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write("Hello World");
      response.end();
    }).listen(1337);
    

    console.log('服务器运行');

    【讨论】:

    【解决方案2】:

    以下是使用 Apache2-Webserver 的可能解决方法:

    只需在 conf.d 中编辑虚拟主机(对于 Ubuntu,您可以在 /etc/apache/ 中找到它),运行 a2enmod proxy 并重新启动 Apache。

    这是一个可能的配置:

    NameVirtualHost *:80
    <VirtualHost *:80>
         ServerName your-domain.com
         ServerAlias www.your-domain.com
         ProxyRequests off
         ProxyPass / http://127.0.0.1:1337/
         ProxyPassReverse / http:/127.0.0.1:1337/
    </VirtualHost>
    

    【讨论】:

    • 谢谢,但是我用的是centos,你能给我正确的配置吗
    • 你会在 /etc/httpd/ 中找到 conf.d。配置与使用 Ubuntu 时相同。
    • 确保您在配置的端口上运行节点应用程序。
    • @ananta 你能把端口改成 80 或 8080 并验证它是否工作。
    • 如何为nodejs配置端口
    【解决方案3】:

    其实很简单。根本不使用任何 IP,只需定义端口即可。

    var http = require('http');
    http.createServer(function (req, res) {
       res.writeHead(200, {'Content-Type': 'text/plain'});
       res.end('Hello World\n');
    }).listen(1337);
    
    console.log('Server running!');
    

    正如 Sach 所说,您不能只将其上传到网络服务器。您必须安装 node 和 npm,并且您必须通过

    实际运行代码

    $ nodejs application.js

    【讨论】: