gpt4 book ai didi

node.js - 如何在同一端口上运行express和geddy应用程序?

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:38 25 4
gpt4 key购买 nike

现有一个使用geddy框架实现的node.js应用程序,它是由Heroku的工头启动的,如下所示:

web: geddy

我正在努力将其制作成 Heroku 插件。 Heroku 有一种方法可以自动生成附加组件所需的框架代码,但它是使用express 实现的。它是通过以下命令启动的:

web: node web.js

在内部,Heroku 仅为每个应用程序分配 1 个端口(将外部流量路由到它)。有没有办法在同一端口上启动现有的geddy 应用程序和附加 Express 应用程序?或者有某种类型的应用程序级路由器可以根据传入请求路径转发到geddy 或express?

最佳答案

假设您在 Heroku 上并且仅限于 Node.js 应用程序,我建议您启动一个新的 Node 实例作为反向代理。一个快速而肮脏的例子如下:

代理.js

var http = require('http'),
httpProxy = require('http-proxy');
var options = {
pathnameOnly: true,
router: {
'/foo': '127.0.0.1:8001',
'/bar': '127.0.0.1:8002'
}
};

var proxyServer = httpProxy.createServer(options);
proxyServer.listen(8000);

第一个.js

var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('I am the first server!\n');
}).listen(8001);

第二个.js

var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('I am the second server!\n');
}).listen(8002);

使用node启动全部三个脚本,测试结果如下:

cloud@wishlist:~$ curl localhost:8000/foo
I am the first server!
cloud@wishlist:~$ curl localhost:8000/bar
I am the second server!

这正是您所需要的:让两个应用程序看起来像是在同一端口上监听。有关更多详细信息,请查看node http-proxy module

关于node.js - 如何在同一端口上运行express和geddy应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20342410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com