如何将响应 headers 修改为 express-http-proxy

How to modify response headers with express-http-proxy

背景

我正在使用 express-http-proxy 来代理我的 SPA(单页应用程序)和 CouchDB 实例之间的一些请求。我在每次调用的基础上执行此代理,而不是创建代理服务器(这在稍后会很重要)。

当前使用示例

app.use(`some/url`, proxy(dburl, {
  forwardPath: req => {return 'some/url'+require('url').parse(req.url).path;}
 }) );

这意味着我没有使用 httpProxy.createServer。我想将一些文本数据片段连同我的回复一起发送为 header。在查看 documentation I've come to the conclusion that what I want will be using intercept. Unfortunately I've not quite managed to grasp how to use it, and the only related questions 之后,我发现到目前为止似乎是基于 httpProxy.createServer 的,它似乎(根据我有限的理解)以不同的方式工作。

我们正在使用单独的请求代理,因为我们希望将不同的请求代理到不同的 micro-services,并且发现这是最简洁的方式(我们知道 & 当时)。

问题

给定代码

const text = 'asdf';
app.use(`some/url`, proxy(dburl, {
  forwardPath: req => {return 'some/url'+require('url').parse(req.url).path;},
  intercept: function(rsp, data, req, res, callback) {
    //SUSPECT LOCATION
  }
}) );

SUSPECT LOCATION 是否有一些代码允许我将 text 放在 header 上作为最终响应而不进一步影响(当前正在工作的)代理?

补充说明

Headers 和一般的网络请求对我来说不是很熟悉,如果答案似乎不言自明,我深表歉意。

link 资源的加分点有助于解释使用此库进行代理的优点、类似的代理库或可以清楚说明如何使用此库的底层技术代理库。也就是说,我宁愿花一些自己的时间进一步研究这个问题,也不想回来询问更多问题。

我不完全相信我的代码会放在 SUSPECT LOCATION 中,如果它需要放在其他地方,或者我们是否需要以不同的方式解决这个问题,我会很乐意倾听。

它在 req、res objects 上遵循 express.js 方法。

在拦截函数 body 中,使用以下快速格式设置响应 headers。

res.set('hola', 'amigos!!!');

参考下面link:
http://expressjs.com/en/4x/api.html#res.set

在没有文档的情况下理解库的最佳方法是遵循其测试套件。如果没有测试套件,请不要使用该库。

这是 express-http-proxy 拦截功能的测试套件
https://github.com/villadora/express-http-proxy/blob/master/test/intercept.js

这是测试用例

it('can modify the response headers', function(done) {
  var app = express();
  app.use(proxy('httpbin.org', {
    intercept: function(rsp, data, req, res, cb) {
      res.set('x-wombat-alliance', 'mammels');
      res.set('content-type', 'wiki/wiki');
      cb(null, data);
    }
  }));

  request(app)
  .get('/ip')
  .end(function(err, res) {
    if (err) { return done(err); }
    assert(res.headers['content-type'] === 'wiki/wiki');
    assert(res.headers['x-wombat-alliance'] === 'mammels');
    done();
  });
});

如果你想了解代理内外,最好的资源是 haproxy
http://cbonte.github.io/haproxy-dconv/1.7/intro.html

不过在此之前你需要多了解一下http(建设性意见)

已接受的答案现已过时。 拦截不再存在。

而是在代理功能之前使用自己的中间件

router.route('/my-route').get((req, res, next) => {
  res.set('My-Header', 'my-header-value');
  next();
}, proxyFunction);