首页 > 解决方案 > 重定向 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);
}

谢谢埃斯图斯!

标签: node.jsexpress

解决方案


这可以通过模拟原始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

推荐阅读