使用2个Node.js和Express应用程序共享端口443(https)的方法?

3
我有一个EC2实例,我在其中托管了一个Node.js应用程序(NodeJS1)。我制作了另一个版本的Node.js应用程序(NodeJS2)。

我已经为EC2实例注册了一个单一域名。

我还设置了EC2安全组,以便https使用443端口 - 似乎没有办法告诉EC2我想要在自定义端口上使用https。

既然唯一可能的https端口是443,那么有没有办法让两个Node.js应用程序共享此端口?

编辑

我还应该提到,我正在使用Express作为我的Node.js应用程序。 我目前是这样启动我的应用程序:

var app = express();
app.set('port', process.env.PORT || 3030);
fs = require('fs')
var sslOptions = {
                key: fs.readFileSync('./mykey.key'),
                cert: fs.readFileSync('./mycert.crt'),
        };
https = require('https').createServer(sslOptions, app);
var server = https.listen(app.get('port'), function (err) {
if (err) throw err;
console.log('listening on ' + server.address().port)
});
另一次更新

我现在正在尝试以下操作:

var httpProxy = require('http-proxy');
var fs = require('fs');
var proxyTable = {};

proxyTable['example.com/baz'] = 'http://localhost:3030';
proxyTable['example.com/buz'] = 'http://localhost:3031';

var httpOptions = {
    router: proxyTable
};
var httpsOptions = {
    router: proxyTable,
    ssl: {
        key: fs.readFileSync('./mykey.key', 'utf8'),
        cert: fs.readFileSync('./mycert.crt','utf8')}
};
httpProxy.createServer(httpsOptions).listen(443, function(err){
        if (err) throw err;
        console.log('proxy listening...');
});

当我运行它时,会得到以下错误:
/home/ec2-user/MacaronicWebApp/node_modules/http-proxy/lib/http-proxy/index.js:119
    throw err;
          ^
Error: Must provide a proper URL as target
    at ProxyServer.<anonymous> (/home/ec2-user/MacaronicWebApp/node_modules/http-proxy/lib/http-proxy/index.js:68:35)
    at Server.closure (/home/ec2-user/MacaronicWebApp/node_modules/http-proxy/lib/http-proxy/index.js:125:43)

我搜索了这个错误,看起来这种方法已经过时了(不再支持),我该如何获得这种行为?


你如何设想确定哪个版本应该获得哪个流量?你可以通过虚拟主机来解决你的问题。 - NG.
1个回答

4

您可以在不同的端口上运行两个分开的应用程序,然后利用npm包http-proxy。使用http-proxy,您可以根据请求的URI在443端口上提供所有内容。

例如:

router: {
   'example.com/nodejs1': 'localhost:4000',
   'example.com/nodejs2': 'localhost:4001',
   ...
}

是的!如果您将 example.com 设置为 SSL 域,您只需获取 URI 并使用代理服务与另一个端口上的节点应用程序进行通信。然后该应用程序将通过代理返回并通过 443 返回。 - Michael Irigoyen
@Micheal 我还有点困惑,我忘了提到我正在使用Express(请参见编辑),http-proxy如何与Express一起工作?谢谢! - A.D
@Micheal,我该如何在你的示例中使用“router”?我在http-proxy文档中没有看到它。 - A.D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接