NodeJS HTTP - 在 80 以外的其他端口上监听
NodeJS HTTP - listen on other port than 80
我正在 运行ning XAMPP 上 Windows 以在端口 80 上托管 Apache 服务器。现在我正在尝试在 运行ning 中安装一个 NodeJS 脚本背景,但问题是它只能在端口 80 上侦听。如果可以,一切正常,但我不能同时拥有 Apache 运行ning,因为 Apache 优先,只为我服务网站。 NodeJS 脚本甚至无法监听。
我的问题是:如何切换 NodeJS 脚本的监听端口(具体端口真的无所谓),这样 Apache 仍然可以 运行 在端口 80 上,我可以访问 NodeJS 脚本来自世界各地。
部分NodeJS代码:
const http = require('http');
const port = 8080;
const host = '0.0.0.0';
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
doStuff(body);
});
res.writeHead(200, {'Content-Type': 'text'});
res.end('received request successfully');
}
else {
res.writeHead(405, {'Content-Type': 'text'});
res.end('not allowed method ' + req.method + ', try again with GET or POST');
}
})
server.listen(port, null, function(error){
if(!!error){
console.log("\x1b[41m%s\x1b[0m", "error while initializing listener on port " + port + ": " + error);
}
else{
console.log("\x1b[32m%s\x1b[0m", "started listener at 'http://" + host + ':' + port + "'");}
});
Additional information is in my other question which got flagged as duplicate.
只需将您的 node.js 服务器端口更改为:
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
其中 8080 是 node.js 服务器的新端口。
看看你的 other question,它被标记为与这个重复,你在那里有一些额外的信息,可能有助于阐明你的需要。具体来说,您提到以下内容:
I want to host multiple http servers with NodeJS, that all get and send http requests. At the same time I want to have Apache running, which occupies port 80. If I disable Apache and let NodeJS run on port 80, it will work but I can't have them running at the same time.
This script will run and receive requests locally at port 8081, but I can't seem to send an AJAX request to it through the Internet, even after forwarding the port with my router:
我认为@ankit-agarwal 可能是正确的,因为您需要一个反向代理设置来将流量转发到不同的后端。假设您有一个面向外部的 IP 地址,您应该能够使用它们正在侦听的端口访问每个后端。例如,如果您的机器暴露的 public IP 地址是 100.120.110.43:
+---------+------+-------------------------------------+
| Backend | Port | Web Address |
+=========+======+=====================================+
| Apache | 80 | 100.120.110.43 or 100.120.110.43:80 |
| Node1 | 8080 | 100.120.110.43:8080 |
| Node2 | 8081 | 100.120.110.43:8081 |
+---------+------+-------------------------------------+
如果你想在不指定端口的情况下访问每个后端,你必须有一些方法来告诉你的内部网络根据请求服务哪个后端。这样做的一种方法是使用基于路径的路由,您可以在其中设置反向代理以根据 url 中的路径将流量路由到不同的后端。您没有 post 您的 Apache 配置,但您可以使用您当前的 Apache 服务器使用类似于下面的 ProxyPass and ProxyPassReverse 指令来处理此问题:
ProxyPass "/node1" "http://100.120.110.43:8080/"
ProxyPassReverse "/node1" "http://100.120.110.43:8080/"
ProxyPass "/node2" "http://100.120.110.43:8081/"
ProxyPassReverse "/node2" "http://100.120.110.43:8081/"
使用反向代理的好处是您不必将节点后端暴露给 public。假设您还没有,并且只能从 0.0.0.0:port.
的内部网络访问它们
Listen 80
<VirtualHost *:80>
DocumentRoot /www/apache
ServerName www.apachefrontend.com
ProxyRequests off
ProxyPass /node1 http://0.0.0.0:8080/
ProxyPassReverse /node1 http://0.0.0.0:8080/
ProxyPass /node2 http://0.0.0.0:8081/
ProxyPassReverse /node2 http://0.0.0.0:8081/
</VirtualHost>
您也可以指向只有您有权访问的其他 hosts/ips。
最后,如果您有不同的 DNS 记录指向不同的后端,您还可以使用 VirtualHost 和 ServerName。
Listen 80
<VirtualHost *:80>
DocumentRoot /www/apache
ServerName www.apachefrontend.com
</VirtualHost>
<VirtualHost *:80>
ServerName www.nodebackend1.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass / http://0.0.0.0:8080/
ProxyPassReverse / http://0.0.0.0:8080/
</Location>
</VirtualHost>
<VirtualHost *:80>
ServerName www.nodebackend2.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass / http://0.0.0.0:8081/
ProxyPassReverse / http://0.0.0.0:8081/
</Location>
</VirtualHost>
要使上述任何一项工作,您需要在 apache 中启用 mod_proxy
和 mod_proxy_http
。
这些可能不是最可靠的例子,我也没有测试过它们,但它们应该可以证明这个想法。您可以了解更多 here.
我还没有真正理解你没有得到任何回应是什么意思,因为我 运行 相同的代码并且它对我来说工作正常。
我只注意到这里(我在评论中为您留了条记录)
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
doStuff(body); //you haven't defined doStuff so you will end up with a error message on this line, but you sever will still run fine
});
res.writeHead(200, {'Content-Type': 'text'});
res.end('received request successfully');
}
else {
res.writeHead(405, {'Content-Type': 'text'});
res.end('not allowed method ' + req.method + ', try again with GET or POST');
}
})
当运行收到你的post请求时,不要忘记在你的body区域添加""
,select raw 然后选择 JSON(application/json)。这应该 运行 适合你,除了你可能会得到 reference error
如下所示,但你仍然应该得到 received request successfully
.
的回应
错误
doStuff(body);
^
ReferenceError: doStuff is not defined
确保您正在做同样的事情,如果您的问题已解决,请告诉我们。
您的 8080
端口上似乎已经 运行 了。只需更改为另一个端口。例如7000
并确保您像这样调用 nodejs 应用程序的所有请求
localhost:7000 // Normal we run at port 80 url simply localhost without port
这与在共享主机中使用 NodeJ 的情况相同。我已经写了一篇关于它的博文 here
让我摘录一下。
Just run the NodeJS server at let's say 8080
port.
Now, let's say your Apache serves at http://example.com, create a folder in your public_html
or www
. let's say the name is server
. So, your new folder path is http://example.com/server
- create a
.htaccess
file in the server folder
add the following lines,
RewriteEngine On
RewriteRule ^$ http://127.0.0.1:8080/ [P,L] #which is your node server ip:port
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:8080/ [P,L] #same ip:port
这会将所有请求从 http://example.com/server
重定向到您的节点服务器。
如果我想在同一个端口中使用 Apache 和 Nodejs:
npm http-代理中间件
1.设置 Apache 端口 = 81
[apache 目录]/conf/httpd.conf
~59: Listen 81
2。设置nodejs APP端口=3050
server.listen(3050);
// on linux ports<1000 require root privilegue
3。使用第三个代理APP(http-proxy-middleware)
// https://www.npmjs.com/package/http-proxy-middleware
var express = require('express');
var proxy = require('http-proxy-middleware');
// proxy middleware options
var options = {
target: 'http://localhost:81', // target host ROOT
changeOrigin: true, // needed for virtual hosted sites
ws: true, // proxy websockets
pathRewrite: {
// '^/api/old-path' : '/api/new-path', // rewrite path
// '^/api/remove/path' : '/path' // remove base path
},
router: {
// Examples:
// when request.headers.host == 'dev.localhost:3000',
// override target 'http://www.example.org' to 'http://localhost:8000'
// 'dev.localhost:3000' : 'http://localhost:8000',
// 'localhost:9000': 'localhost:9002/sub',
// '/sub': 'http://localhost:9002',
'localhost': 'http://localhost:81', //Root to Apache
'sub.localhost': 'http://localhost:3050', // internal
'sub.mydomain.com': 'http://localhost:3050', //external
},
};
// create the proxy (without context)
// var proxy_wp = proxy(options_wp);
var proxy_node = proxy(options);
// mount `exampleProxy` in web server
var app = express();
app.use(proxy_node);
app.listen(80);
然后:
- localhost:80 - 是 apache 站点
- sub.localhost:80 - 节点
- localhost:80/sub - 节点,如果你设置
对于任务运行程序,我使用 npm PM2
我正在 运行ning XAMPP 上 Windows 以在端口 80 上托管 Apache 服务器。现在我正在尝试在 运行ning 中安装一个 NodeJS 脚本背景,但问题是它只能在端口 80 上侦听。如果可以,一切正常,但我不能同时拥有 Apache 运行ning,因为 Apache 优先,只为我服务网站。 NodeJS 脚本甚至无法监听。
我的问题是:如何切换 NodeJS 脚本的监听端口(具体端口真的无所谓),这样 Apache 仍然可以 运行 在端口 80 上,我可以访问 NodeJS 脚本来自世界各地。
部分NodeJS代码:
const http = require('http');
const port = 8080;
const host = '0.0.0.0';
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
doStuff(body);
});
res.writeHead(200, {'Content-Type': 'text'});
res.end('received request successfully');
}
else {
res.writeHead(405, {'Content-Type': 'text'});
res.end('not allowed method ' + req.method + ', try again with GET or POST');
}
})
server.listen(port, null, function(error){
if(!!error){
console.log("\x1b[41m%s\x1b[0m", "error while initializing listener on port " + port + ": " + error);
}
else{
console.log("\x1b[32m%s\x1b[0m", "started listener at 'http://" + host + ':' + port + "'");}
});
Additional information is in my other question which got flagged as duplicate.
只需将您的 node.js 服务器端口更改为:
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
其中 8080 是 node.js 服务器的新端口。
看看你的 other question,它被标记为与这个重复,你在那里有一些额外的信息,可能有助于阐明你的需要。具体来说,您提到以下内容:
I want to host multiple http servers with NodeJS, that all get and send http requests. At the same time I want to have Apache running, which occupies port 80. If I disable Apache and let NodeJS run on port 80, it will work but I can't have them running at the same time.
This script will run and receive requests locally at port 8081, but I can't seem to send an AJAX request to it through the Internet, even after forwarding the port with my router:
我认为@ankit-agarwal 可能是正确的,因为您需要一个反向代理设置来将流量转发到不同的后端。假设您有一个面向外部的 IP 地址,您应该能够使用它们正在侦听的端口访问每个后端。例如,如果您的机器暴露的 public IP 地址是 100.120.110.43:
+---------+------+-------------------------------------+
| Backend | Port | Web Address |
+=========+======+=====================================+
| Apache | 80 | 100.120.110.43 or 100.120.110.43:80 |
| Node1 | 8080 | 100.120.110.43:8080 |
| Node2 | 8081 | 100.120.110.43:8081 |
+---------+------+-------------------------------------+
如果你想在不指定端口的情况下访问每个后端,你必须有一些方法来告诉你的内部网络根据请求服务哪个后端。这样做的一种方法是使用基于路径的路由,您可以在其中设置反向代理以根据 url 中的路径将流量路由到不同的后端。您没有 post 您的 Apache 配置,但您可以使用您当前的 Apache 服务器使用类似于下面的 ProxyPass and ProxyPassReverse 指令来处理此问题:
ProxyPass "/node1" "http://100.120.110.43:8080/"
ProxyPassReverse "/node1" "http://100.120.110.43:8080/"
ProxyPass "/node2" "http://100.120.110.43:8081/"
ProxyPassReverse "/node2" "http://100.120.110.43:8081/"
使用反向代理的好处是您不必将节点后端暴露给 public。假设您还没有,并且只能从 0.0.0.0:port.
的内部网络访问它们Listen 80
<VirtualHost *:80>
DocumentRoot /www/apache
ServerName www.apachefrontend.com
ProxyRequests off
ProxyPass /node1 http://0.0.0.0:8080/
ProxyPassReverse /node1 http://0.0.0.0:8080/
ProxyPass /node2 http://0.0.0.0:8081/
ProxyPassReverse /node2 http://0.0.0.0:8081/
</VirtualHost>
您也可以指向只有您有权访问的其他 hosts/ips。
最后,如果您有不同的 DNS 记录指向不同的后端,您还可以使用 VirtualHost 和 ServerName。
Listen 80
<VirtualHost *:80>
DocumentRoot /www/apache
ServerName www.apachefrontend.com
</VirtualHost>
<VirtualHost *:80>
ServerName www.nodebackend1.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass / http://0.0.0.0:8080/
ProxyPassReverse / http://0.0.0.0:8080/
</Location>
</VirtualHost>
<VirtualHost *:80>
ServerName www.nodebackend2.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass / http://0.0.0.0:8081/
ProxyPassReverse / http://0.0.0.0:8081/
</Location>
</VirtualHost>
要使上述任何一项工作,您需要在 apache 中启用 mod_proxy
和 mod_proxy_http
。
这些可能不是最可靠的例子,我也没有测试过它们,但它们应该可以证明这个想法。您可以了解更多 here.
我还没有真正理解你没有得到任何回应是什么意思,因为我 运行 相同的代码并且它对我来说工作正常。
我只注意到这里(我在评论中为您留了条记录)
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
doStuff(body); //you haven't defined doStuff so you will end up with a error message on this line, but you sever will still run fine
});
res.writeHead(200, {'Content-Type': 'text'});
res.end('received request successfully');
}
else {
res.writeHead(405, {'Content-Type': 'text'});
res.end('not allowed method ' + req.method + ', try again with GET or POST');
}
})
当运行收到你的post请求时,不要忘记在你的body区域添加""
,select raw 然后选择 JSON(application/json)。这应该 运行 适合你,除了你可能会得到 reference error
如下所示,但你仍然应该得到 received request successfully
.
错误
doStuff(body);
^
ReferenceError: doStuff is not defined
确保您正在做同样的事情,如果您的问题已解决,请告诉我们。
您的 8080
端口上似乎已经 运行 了。只需更改为另一个端口。例如7000
并确保您像这样调用 nodejs 应用程序的所有请求
localhost:7000 // Normal we run at port 80 url simply localhost without port
这与在共享主机中使用 NodeJ 的情况相同。我已经写了一篇关于它的博文 here
让我摘录一下。
Just run the NodeJS server at let's say
8080
port.Now, let's say your Apache serves at http://example.com, create a folder in your
public_html
orwww
. let's say the name isserver
. So, your new folder path is http://example.com/server- create a
.htaccess
file in the server folderadd the following lines,
RewriteEngine On RewriteRule ^$ http://127.0.0.1:8080/ [P,L] #which is your node server ip:port RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ http://127.0.0.1:8080/ [P,L] #same ip:port
这会将所有请求从 http://example.com/server
重定向到您的节点服务器。
如果我想在同一个端口中使用 Apache 和 Nodejs: npm http-代理中间件
1.设置 Apache 端口 = 81
[apache 目录]/conf/httpd.conf
~59: Listen 81
2。设置nodejs APP端口=3050
server.listen(3050); // on linux ports<1000 require root privilegue
3。使用第三个代理APP(http-proxy-middleware)
// https://www.npmjs.com/package/http-proxy-middleware
var express = require('express');
var proxy = require('http-proxy-middleware');
// proxy middleware options
var options = {
target: 'http://localhost:81', // target host ROOT
changeOrigin: true, // needed for virtual hosted sites
ws: true, // proxy websockets
pathRewrite: {
// '^/api/old-path' : '/api/new-path', // rewrite path
// '^/api/remove/path' : '/path' // remove base path
},
router: {
// Examples:
// when request.headers.host == 'dev.localhost:3000',
// override target 'http://www.example.org' to 'http://localhost:8000'
// 'dev.localhost:3000' : 'http://localhost:8000',
// 'localhost:9000': 'localhost:9002/sub',
// '/sub': 'http://localhost:9002',
'localhost': 'http://localhost:81', //Root to Apache
'sub.localhost': 'http://localhost:3050', // internal
'sub.mydomain.com': 'http://localhost:3050', //external
},
};
// create the proxy (without context)
// var proxy_wp = proxy(options_wp);
var proxy_node = proxy(options);
// mount `exampleProxy` in web server
var app = express();
app.use(proxy_node);
app.listen(80);
然后:
- localhost:80 - 是 apache 站点
- sub.localhost:80 - 节点
- localhost:80/sub - 节点,如果你设置
对于任务运行程序,我使用 npm PM2