我们的实验室有一个简单的 Nodejs 流程用于测试/开发工作。我们正在使用node-proxy设置反向代理,使我们能够使用 http(即 http -> https)与 https 服务器进行通信。作为其中的一部分,我们有一些用于修改响应的代码。这是我们正在做的事情:
var http = require('http'),
httpProxy = require('http-proxy'),
endserver = 'server.local',
endport = 8443;
var proxy = new httpProxy.HttpProxy({
target: {
https: true,
host: endserver,
port: endport
}
});
http.createServer(function (req, res) {
//our code for modifying response is here...
proxy.proxyRequest(req, res);
}).listen(8001);
我想设置一个 Node 代理路由表,就像这个例子here ,因此我可以根据请求中的主机名将请求转发到不同的 https 服务器(我将在 dns 上设置多个主机名,指向运行 Nodejs 代理的同一服务器)。
如何拥有 Node 代理路由表并修改响应?
(我对 Node.js 很陌生,但对 javascript 不太熟悉)
最佳答案
如果我正确地阅读了您的问题,您只需要知道如何使用 Node 代理路由表根据请求对象路由不同主机的请求。这实际上是由 node-http-proxy 文档解决的: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
}
});
});
}
};
关于node.js - nodejs Node 代理,使用路由表并修改响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13683655/