【问题标题】:Node - express-http-proxy - set Header before proxying节点 - express-http-proxy - 在代理之前设置 Header
【发布时间】:2018-12-06 16:01:00
【问题描述】:

在我代理到一个地址之前,我想设置代理的标头(Smth 就像一个拦截器)。我使用 express-http-library 并使用 Node.JS 表达。到目前为止,我的代码如下所示。顺便提一句。这个库的文档并没有让我变得更聪明。

app.use('/v1/*', proxy('velodrome.usefixie.com', {
userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) {
    // recieves an Object of headers, returns an Object of headers.
    headers = {
        Host: 'api.clashofclans.com',
        'Proxy-Authorization': `Basic ${new Buffer('token').toString('base64')}`
    };
    console.log(headers);

    return headers;
}

}));

即使控制台将我打印出标题 obj。正如预期的那样,代理授权不起作用:

{ Host: 'api.clashofclans.com',
  'Proxy-Authorization': 'Basic token' }

谁能帮帮我?

【问题讨论】:

  • 我提供的答案比已接受的答案更完整,即使在 3 年后的现在,它仍在继续获得支持...您能否将我的答案标记为已接受的答案?

标签: node.js http express proxy


【解决方案1】:

如果您需要做的只是添加一些中间件来更改一些标头,您应该可以这样做:

app.use('/v1/*', (req, res, next) => {
    req.headers['Proxy-Authorization'] = `Basic ${new Buffer('token').toString('base64')}`;
    next();
});

【讨论】:

    【解决方案2】:

    express-http-proxy 允许您通过proxyReqOptDecorator 传入选项对象(与request 库中使用的对象相同):

    app.use("/proxy", proxy("https://target.io/api", {
      proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
        proxyReqOpts.headers = {"Authorization": "Bearer token"};
        return proxyReqOpts;
      }
    }));
    
    

    app.use("/proxy", proxy("https://target.io/api", {
      proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
        proxyReqOpts.auth = `${username}:${password}`;
        return proxyReqOpts;
      }
    }));
    

    proxyReqOptDecorator 的文档可以在 here 找到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      相关资源
      最近更新 更多