我想捕获“请求”发出的异步调用。
我要监听的呼叫是“ 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' });
});
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);
}
感谢Estus!
答案 0 :(得分:1)
这可以通过模拟原始proxyquire
模块来完成。
这大致是const originalRequest = require('request');
function patchedRequest(url, ...args) {
const newUrl = 'https://www.google.com/' // replace url with another one;
return originalRequest(newUrl, ...args);
}
Object.assign(patchedRequest, originalRequest);
for (const verb of 'get,head,options,post,put,patch,del,delete'.split(',')) {
patchedRequest[verb] = function (url, ...args) {
const newUrl = 'https://www.google.com/' // replace url with another one;
return originalRequest[verb](newUrl, ...args);
};
}
module.exports = require.cache[require.resolve('request')].exports = patchedRequest;
之类的缓存管理库的工作方式:
patch-request.js
// patch request before it's required anywhere else
require('./patch-request');
// load the app that uses request
index.js
<custom-directive>
<ng-container ng-repeat="item in items">
{{item.description}}
</ng-container>
</custom-directive>