我正在尝试向我的 node-http-proxy 中的原始请求添加新的查询参数, 像这样直接调整 req.query
是行不通的:
app.all(path, function (req, res) {
req.query.limit = 2;
apiProxy.web(req, res, { target: target });
});
limit
参数未被目标接收。
我想用这种方式隐藏 API key ,是否可以添加新的查询参数?
最佳答案
我猜你使用的方法是在响应之后。需要使用proxyReq
事件
var httpProxy = require('http-proxy');
const url = require('url');
proxy = httpProxy.createServer({
target: 'https://httpbin.org',
secure: false
}).listen(8009);
proxy.on('proxyReq', function(proxyReq, req, res, options) {
parsed = url.parse(proxyReq.path, true);
parsed.query['limit'] = 2
updated_path = url.format({pathname: parsed.pathname, query: parsed.query});
proxyReq.path = updated_path
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});
结果
$ curl "http://localhost:8009/get?x=yz2"
{
"args": {
"limit": "2",
"x": "yz2"
},
"headers": {
"Accept": "*/*",
"Host": "localhost",
"User-Agent": "curl/7.54.0",
"X-Special-Proxy-Header": "foobar"
},
"origin": "36.255.84.232, 36.255.84.232",
"url": "https://localhost/get?x=yz2&limit=2"
}
关于javascript - node-http-proxy,如何将新的查询参数传递给初始请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55285448/