I would like to capture an async call made by "request".
The call I am looking to intercept is "https://api.ap.org/v2/yada/yada" .
I want to intercept this third party call to api.ap.org and redirect it to another service, say 127.0.0.1:3001.
I would also like to add headers during this intercept process.
I know how to intercept all calls made by the express js route via http-proxy, but this does not intercept calls made within nodejs itself.
router.get('/', function(req, res, next) {
request("https://api.ap.org/v2/yada/yada", {}, (err, data) => {
console.log('---- call made')
console.log(data);
});
res.render('index', { title: 'Express' });
});
UPDATE - from Estus
function patchedRequest(url, options, ...args) {
let newUrl = 'https://www.google.com/' // replace url with another one;
console.log('------ args');
console.log(url);
console.log(options);
if(url.match(/api\.ap\.org/).length){
options = {};
newUrl = 'http://127.0.0.1:3000/api'
}
return originalRequest(newUrl, options, ...args);
}
- This allows me to intercept the call to the third party API and send it the service of my choosing.
Thanks Estus!
request, withrewireor something. Or proxy Node requests globally, stackoverflow.com/questions/18586902/… . Or specify a proxy just forrequest, github.com/request/… . The actual solution depends on how things are done in your case.requestitself is a singleton. JS modules are singletons by definition.require('request') === require('request'). You can create a wrapper withproxyquire(I don't think thatrewiredoes the job) or else instead of forkingrequest.