【问题标题】:Node js can connect internally but not externallyNode js 可以内部连接但不能外部连接
【发布时间】:2014-09-29 17:20:27
【问题描述】:

我正在尝试连接到本地服务器上的 js 文件。我希望能够输入外部 IP 地址和端口并让它在外部运行应用程序。目前可以在本地执行此操作。这是我的 server.js 文件代码:

var express = require('express');
var app     = express();

var mysql   = require('mysql');

var connectionpool = mysql.createPool({
  host     : '127.0.0.1',
  user     : 'root',
  password : '',
  database : 'development',
  port: 3306,
  connectionLimit: 50
});
var UAParser = require('ua-parser-js');
var bodyParser = require('body-parser');

// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public')); 
app.use(express.logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
})); // pull information from html in POST


require('./config/signup.js')(app, express, connectionpool, UAParser);

//Setup for external access
var http = require('http');
http.createServer(function(req, res){
  //res.writeHead(200, {'content-type': 'text/plain'});
  //res.end('It works');
}).listen(8080);

// Start app on port 8080
/*app.listen(8080);
console.log('Rest Demo Listening on port 8080');*/

目前我可以从外部连接到服务器,但最终会进入默认主页,该主页只是一小段文字。我希望能够输入外部 IP 地址和端口并让它立即开始运行我的应用程序,而无需浏览目录。如果这有任何帮助,我也在运行 apache。

固定: 这行代码代替了 http.createServer 函数使其工作

var server = http.createServer(app).listen(8080);

【问题讨论】:

  • 您是使用 8080 端口直接访问应用程序,还是使用 Apache 通过 mod_proxy 代理它?
  • 听起来你是在打 apache 而不是 node。杀死 apache 并将 8080 更改为 80。您可能必须获得超级用户权限才能侦听该端口。
  • 连接apache(80/8080端口)或mysql(3306)不起作用?
  • Killed apache 但是当我尝试监听端口 80 时出现错误:监听 EACCES。如何获得超级用户权限来监听该端口?

标签: javascript node.js apache nodemon


【解决方案1】:

您可以像这样调整/创建您的 apache 配置:

<VirtualHost *:80>
    ServerName (SERVER NAME HERE)
    ServerAlias  (SERVER ALIAS HERE)
    ErrorLog "/var/log/httpd/nodejs-error.log"
    CustomLog "/var/log/httpd/nodejs-access.log" common

    #######################
    # Redirect to node.js #
    #######################
    ProxyRequests Off
    ProxyPreserveHost On

    ProxyPass               /            http://localhost:8080/
    ProxyPassReverse        /            http://localhost:8080/

</VirtualHost>

你应该把它放在你的 apache conf.d 目录(通常是 /etc/httpd/conf.d)中的一个像“nodejs.conf”这样的文件中。

编辑:注意 - 如果您使用默认的 apache 配置,它位于 conf 目录中并命名为 httpd.conf。您可以编辑其中的 VirtualHost 条目以匹配上面的内容。

【讨论】:

  • 这样我就可以同时运行 apache 和 nodejs 了吗?
  • 就是这样——是的。 Apache 会将所有请求代理到节点。这样你就不需要运行带有时髦权限的 nodejs。
  • 那会是启用 conf 的文件夹吗?
  • 如果您实际上是在使用 apache 托管东西,那么您可以将它们设置为其他值 (/node),而不是将 ProxyPass 和 ProxyPassReverse 设置为 root (/),它只会代理到节点那条路。
  • 你使用的是什么 Linux 发行版?在我的 debian/ubuntu/centos 服务器上,配置位于 /etc/httpd/conf 和 /etc/httpd/conf.d。
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
相关资源
最近更新 更多