Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-http-proxy, how to pass new query parameters to initial request?

I am trying to add new query params to the original request in my node-http-proxy, tweaking the req.query directly like this doesn't work:

app.all(path, function (req, res) {
    req.query.limit = 2;
    apiProxy.web(req, res, { target: target });
});

The limit param is not received by the target.

I'd like to hide an API key this way, Is it possible to add new query params?

like image 736
randomguy04 Avatar asked Apr 07 '26 01:04

randomguy04


1 Answers

The method your are using is for after the response I guess. The need to use the proxyReq event

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');
});

and the results

$ 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"
}
like image 168
Tarun Lalwani Avatar answered Apr 09 '26 15:04

Tarun Lalwani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!