【问题标题】:Using Express proxy, how to change the relative url?使用 Express 代理,如何更改相对 url?
【发布时间】:2016-02-02 14:17:05
【问题描述】:

为了避免客户端 javascript 代码的典型 CORS 问题,我使用了 nodejs express 服务器。此服务器包含以下代码:

var app = express();

  app.all('/Api/*', function (req, res) {
    proxy.web(req, res, {
        target: 'https://www.myserver.com',
        changeOrigin:true
    });
  });

所以它的作用是将任何以/Api 开头的调用重定向到我的服务器。

不过,这也会将Api 附加到url 路径,所以Api/getData 变成https://www.myserver.com/Api/getData

有没有办法去除相对 url 的 Api 部分?最终结果将是 Api/getData 变为 https://www.myserver.com/getData

这将允许我通过更改相对 url 路径的第一部分来定位多个服务器。像这样的:

Api/getData -> https://www.myserver.com/getData

OtherApi/getData/for/some/path -> https://www.some-other-server.com/getData/for/some/path

这当然适用于所有请求类型,不仅适用于GET

谢谢!

【问题讨论】:

    标签: javascript node.js express node-http-proxy


    【解决方案1】:

    看看http-proxy-rules 模块,它是node-http-proxy 的配套模块。它允许您编写规则以将匹配路由更改为不同的代理路由。

    有了它,您应该能够像这样定义您的翻译:

    var proxyRules = new HttpProxyRules({
        rules: {
          '.*/Api': 'http://myserver.com/', // Rule (1)
          '.*/OtherApi*': 'http://some-other-server.com:8080/' // Rule (2)
        },
        default: 'http://myserver.com/' // default target
      });
    

    然后像这样使用它们:

    app.all('*', function(req, res) {
      var target = proxyRules.match(req);
      if (target) {
        return proxy.web(req, res, {
          target: target
        });
      }
    })
    

    【讨论】:

    • 有趣!中间件太多了,很难知道存在什么。
    【解决方案2】:

    您可以尝试修改req.url 选项。比如:

    app.all('/Api/*', function (req, res) {        
        req.url = req.url.split('/Api/')[1];
        proxy.web(req, res, {
            target: 'http://stackoverflow.com/',
            changeOrigin:true
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 2013-06-10
      • 2011-11-23
      • 2018-03-22
      • 2013-04-29
      • 2011-10-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      相关资源
      最近更新 更多