【发布时间】:2018-09-12 17:11:19
【问题描述】:
我想捕获“请求”发出的异步调用。
我要拦截的电话是 "https://api.ap.org/v2/yada/yada" 。
我想拦截对 api.ap.org 的第三方调用并将其重定向到另一个服务,例如 127.0.0.1:3001。
我还想在这个拦截过程中添加标头。
我知道如何拦截 express js 路由通过 http-proxy 进行的所有调用,但这不会拦截 nodejs 本身内部进行的调用。
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' });
});
更新 - 来自 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);
}
- 这允许我拦截对第三方 API 的调用并将其发送给我选择的服务。
感谢埃斯图斯!
【问题讨论】:
-
这不会拦截在 nodejs 本身内进行的调用 - 究竟什么不起作用?回调没有被调用吗?
-
长话短说,我无法更改此应用程序中的代码。我只能添加一个外部应用程序或将一些代码添加到条目“app.js”文件中。对第三方端点进行了数千次调用。我需要重定向所有这些,但我使用 api.ap.org 作为起点。
-
您可以模拟
request,使用rewire或其他东西。或全局代理节点请求,stackoverflow.com/questions/18586902/…。或者为request、github.com/request/… 指定一个代理。实际的解决方案取决于您的情况是如何完成的。 -
"request" 需要数千次。每个 require 都是一个新实例。我不认为“请求”使他们的模块成为单例。我将不得不分叉回购并在“请求”模块中添加一个钩子并使用我的叉子。我尝试将 nginx 用作非透明转发代理,但也遇到了问题。
-
request本身就是一个单例。 JS 模块根据定义是单例的。require('request') === require('request')。您可以使用proxyquire创建一个包装器(我不认为rewire可以完成这项工作),或者不要分叉request。