【发布时间】:2023-04-11 06:44:04
【问题描述】:
我在 Windows 上运行 XAMPP 以在端口 80 上托管 Apache 服务器。现在我试图让 NodeJS 脚本在后台运行,但问题是它只能在端口 80 上侦听。如果是这样,一切可以正常工作,但我不能同时运行 Apache,因为 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.
【问题讨论】:
-
您需要为此设置反向代理。谷歌一下
-
@AnkitAgarwal 谢谢,我会查一下
-
更改端口时遇到什么错误?
-
@willascend 抱歉回复晚了。我没有错误。它正常启动。它只是无法获取任何数据。
-
知道了。这表明服务器可能在指定的端口上运行。听起来问题是在不使用 url 中的端口的情况下访问节点服务器。请尝试反向代理以使其正常工作。它还可能有助于提供有关您如何设置 apache 服务器以及您希望如何从外部访问节点服务器的其他信息。