最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在nodejs express app中重定向由npm模块“request”发出的异步调用

运维笔记admin6浏览0评论

在nodejs express app中重定向由npm模块“request”发出的异步调用

在nodejs express app中重定向由npm模块“request”发出的异步调用

我想捕获“请求”发出的异步调用。 我希望拦截的电话是“”。

我想拦截这个第三方调用api.ap并将其重定向到另一个服务,比如127.0.0.1:3001。

我还想在拦截过程中添加标题。

我知道如何拦截快速js路由通过http-proxy进行的所有调用,但这并不拦截在nodejs内部进行的调用。

 router.get('/', function(req, res, next) {
   request("", {}, (err, data) => {
       console.log('---- call made')
       console.log(data);
    });
   res.render('index', { title: 'Express' });
 });

UPDATE - from Estus

function patchedRequest(url, options, ...args) {
  let newUrl = '/' // replace url with another one;
  console.log('------ args');
  console.log(url);
  console.log(options);
  if(url.match(/api\.ap\/).length){
      options = {};
      newUrl = 'http://127.0.0.1:3000/api'
  }
  return originalRequest(newUrl, options, ...args);
}
  • 这允许我拦截对第三方API的调用并向其发送我选择的服务。

谢谢你!

回答如下:

这可以通过模拟原始的request模块来完成。

这大致是像proxyquire这样的高速缓存修复库如何工作:

补丁request.js

const originalRequest = require('request');

function patchedRequest(url, ...args) {
  const newUrl = 'https://www.google/' // 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/' // 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
发布评论

评论列表(0)

  1. 暂无评论