如果我正確地讀你的問題,你只需要知道基於請求對象上使用節點 - 不同的主機如何請求路由代理路由表。這實際上是由節點HTTP代理文檔解決:Proxy requests using a ProxyTable
粘貼過來,你只需要在一個JS對象這樣的配置路徑:
var options = {
router: {
'foo.com/baz': '127.0.0.1:8001',
'foo.com/buz': '127.0.0.1:8002',
'bar.com/buz': '127.0.0.1:8003'
}
};
然後通過當你在這個對象您的代理服務器:
var proxyServer = httpProxy.createServer(options);
proxyServer.listen(80);
在一些指定此爲您的代碼的結果是這樣的:
var http = require('http'),
httpProxy = require('http-proxy'),
endserver = 'server.local',
endport = 8443;
var options = {
router: {
endserver + '/foo': '127.0.0.1:8081',
endserver + '/bar': '127.0.0.1:8082',
endserver + '/baz': '127.0.0.1:8083'
}
};
var proxyServer = httpProxy.createServer(options);
proxyServer.listen(endport);
http.createServer(function (req, res) {
// your code for modifying response is here...
proxy.proxyRequest(req, res);
}).listen(8001);
使用路由器選項時無需自己設置目標。看起來https的區別也被處理,但我不確定。我從proxy-table.js source得到了這個信息。特別是:
ProxyTable.prototype.setRoutes = function (router) {
if (!router) {
throw new Error('Cannot update ProxyTable routes without router.');
}
var self = this;
this.router = router;
if (this.hostnameOnly === false) {
this.routes = [];
Object.keys(router).forEach(function (path) {
if (!/http[s]?/.test(router[path])) {
router[path] = (self.target.https ? 'https://' : 'http://')
+ router[path];
}
var target = url.parse(router[path]),
defaultPort = self.target.https ? 443 : 80;
//
// Setup a robust lookup table for the route:
//
// {
// source: {
// regexp: /^foo.com/i,
// sref: 'foo.com',
// url: {
// protocol: 'http:',
// slashes: true,
// host: 'foo.com',
// hostname: 'foo.com',
// href: 'http://foo.com/',
// pathname: '/',
// path: '/'
// }
// },
// {
// target: {
// sref: '127.0.0.1:8000/',
// url: {
// protocol: 'http:',
// slashes: true,
// host: '127.0.0.1:8000',
// hostname: '127.0.0.1',
// href: 'http://127.0.0.1:8000/',
// pathname: '/',
// path: '/'
// }
// },
//
self.routes.push({
source: {
regexp: new RegExp('^' + path, 'i'),
sref: path,
url: url.parse('http://' + path)
},
target: {
sref: target.hostname + ':' + (target.port || defaultPort) + target.path,
url: target
}
});
});
}
};