【发布时间】:2011-09-08 10:30:17
【问题描述】:
我有 3 个 node.js 应用程序(A、B、C)。 A 是一个入口点,我喜欢将所有到达该入口点的请求重定向到 B 或 C(取决于请求中参数的值)。
目前我正在 A 中使用 res.redirect(我使用的是 expressjs 框架)。这工作正常,只是它不是真正透明的(我可以从外部看到原始请求已被重定向)。
为了解决这个问题,我会让 B 和 C 监听套接字而不是端口号,但我不知道如何让 A 将请求重定向到 B 或 C 使用的套接字。
关于如何让 2 个 node.js 进程通过套接字进行通信的任何想法?
** 更新 **
I have changed the code of A to use node-proxy:
app.all('/port/path/*', function(req, res){
// Host to proxied to
var host = 'localhost';
// Retrieve port and build new URL
var arr_url = req.url.split('/');
var port = arr_url[1];
var new_url = '/' + arr_url.slice(2).join('/');
console.log("CURRENT URL:" + req.url); // url is /5000/test/...
console.log("NEW URL :" + new_url); // url is /test/...
// Change URL
req.url = new_url;
var proxy = new httpProxy.HttpProxy();
proxy.proxyRequest(req, res, {
host: host,
port: port,
enableXForwarded: false,
buffer: proxy.buffer(req)
});
console.log("Proxied to " + host + ':' + port + new_url);
// For example: the url is localhost:10000/5000/test
// the log tells me 'Proxied to localhost:5000/test' => that is correct
// But... I do not get any return
// If I issue 'curl -XGET http://localhost:5000/test' I get the return I expect
});
这有什么明显的错误吗?
【问题讨论】:
-
A、B、C 都是 Web 服务吗?
-
是的,所有的网络服务都有,但我不想把 B 和 C 暴露在外面。
-
乔希有正确的答案:将 B 和 C 绑定到
localhost,这样它们就不会暴露给外界,然后将 A 写为反向代理。 (或者使用nginx,如果A只是一个交换机。)