node.js - 重定向 nodejs express 应用程序中 npm 模块“请求”发出的异步调用
问题描述
我想捕获由“请求”发出的异步调用。
我要拦截的电话是“ https://api.ap.org/v2/yada/yada ”。
我想拦截对 api.ap.org 的第三方调用并将其重定向到另一个服务,比如 127.0.0.1:3001。
我还想在这个拦截过程中添加标题。
我知道如何通过 http-proxy 拦截 express js 路由所做的所有调用,但这不会拦截 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);
}
- 这允许我拦截对第三方 API 的调用并将其发送给我选择的服务。
谢谢埃斯图斯!
解决方案
这可以通过模拟原始request
模块来完成。
这大致是缓存修改库的proxyquire
工作方式:
补丁请求.js
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;
index.js
// patch request before it's required anywhere else
require('./patch-request');
// load the app that uses request
推荐阅读
- python - 执行以下代码时出现值错误
- csv - AWK:基于两列的数据后处理
- c++ - 如何从 const 映射中获取元素?
- automated-tests - Robot Framework + Appium 获取元素位置问题?
- android - 在android中进行网络结帐时获取空对象引用
- django - Django Rest Framework 是否对 SerializerMethodField 执行查询
- java - 使用 Apache 客户端时如何记录 Jersey 客户端请求
- javascript - 使用javascript代码将多页tiff图像转换为pdf
- node.js - fsPromises.writeFile() 终止我的服务器
- php - 如何在“使用特征”中放置变量