【问题标题】:Custom response with http-proxy-middleware package使用 http-proxy-middleware 包的自定义响应
【发布时间】:2019-01-02 11:16:44
【问题描述】:

在我们的项目中,我们使用“http-proxy-middleware”(https://www.npmjs.com/package/http-proxy-middleware) npm 包进行代理。

有“onProxyRes”功能订阅http-proxy的事件。

还有一个该功能的示例:

function onProxyRes(proxyRes, req, res) {
  proxyRes.headers['x-added'] = 'foobar' // add new header to response
  delete proxyRes.headers['x-removed'] // remove header from response
}

我很感兴趣,是否有可能基于 proxyRes 在 res 对象中写入更改的响应并且不直接从 proxyRes 对象复制数据?

举例:

proxyRes(可读流包含以下数据:{“url”:“http://domain/test”},我想修改该响应并使用类似数据的 res:{{“url”:“http://changedDomain/test "}} 并且不要直接从proxyRes复制数据

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    也许它看起来有点难看,但我可以使用以下代码来管理它:

    function onProxyRes(proxyResponse, request, serverResponse) {
      var body = "";
      var _write = serverResponse.write;
      proxyResponse.on('data', function (chunk) {
        body += chunk;
      });
    
      serverResponse.write = function (data) {
        try{
          var jsonData = JSON.parse(data);
          // here we can modify jsonData
          var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
          _write.call(serverResponse,buf);
        } catch (err) {
          console.log(err);
        }
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      我认为没有必要将数据复制到res,因为proxyRes 已经有changedDomain。 这是我实现的设置:

      const express = require('express');
      const httpProxy = require('http-proxy-middleware');
      
      const app = express();
      
      app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})
      
      function onProxyRes (proxyResponse, request, response) {
        console.log('proxyResponse', proxyResponse.headers);  
        console.log('response', response.headers);
      }
      
      // Results
      /*
      proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
        server: 'Apache',
        location: 'http://sometarget.com/api',
        'cache-control': 'max-age=30',
        expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
        'content-length': '231',
        connection: 'close',
        'content-type': 'text/html; charset=iso-8859-1' }
      response undefined
      */
      

      您需要的一切都在proxyRes 中,除非您对response 有特定用途...

      【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多