【问题标题】:Node Proxy - Proxy a SSL localhost target from a basic http server节点代理 - 从基本 http 服务器代理 SSL localhost 目标
【发布时间】:2017-05-11 09:56:27
【问题描述】:

我想做的事:

代理一个在https://127.0.0.1:443/api/ 上运行的java api,以及在非SSL http://127.0.0.1:1337/ 上运行的我的UI,以解决一些CORS 问题。

我的尝试:

  1. 将 SSL 端口 443 处的 api 代理到我的非 SSL 开发端口 1338。
  2. 将我的 UI 代理到 1337
  3. 代理 1137 到 :8080/index.html 和代理 1338 到 :8080/api/
  4. 从 localhost:8080 访问我的应用

我的问题:

用户界面很好......但我无法在:8080/api/httpSession/init访问API

是的,我仍然可以通过 https://localhost/api/httpSession/init 访问 API

api.js - 在 :1337 处呈现 index.html

var app = express();

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

var options = {
  changeOrigin: true,
  target: {
      https: true
  }
};

httpProxy.createServer(443, '127.0.0.1', options).listen(1338);

start.js - 代理 1337 和 1338 到 8080

// First I start my two servers
uiServer.start(); // renders index.html at 1337
apiServer.start(); // 

// I attempt to patch them back into one single non-SSL port.
app
  .use('/', proxy({target: 'http://localhost:1337/'}))
  .all('/api/*', proxy({target: 'http://localhost:1338/'}))
  .listen(8080, function () {
    console.log('PROXY SERVER listening at http://localhost:%s', 8080);
  });

【问题讨论】:

  • 我建议你使用 nginx 作为反向代理来实现你所需要的。 Here 是一些说明,可以实现类似于您需要的东西。 This 也应该有帮助...
  • 您是否有理由两次代理您的 api?首先到端口 1338,然后到端口 8080 在 /api/?
  • 我知道这是题外话,但您也可以使用带有反向代理的 Web 服务器在同一端口上实现此目的。例如,您可以使用 IIS 或 Nginx 在一个虚拟服务器上分离反向代理端点。

标签: node.js ssl proxy


【解决方案1】:

您正在寻找的是request piping。试试这个例子:

  // Make sure request is in your package.json
  //   if not, npm install --save request
  var request = require('request');

  // Intercept all routes to /api/...
  app.all('/api/*', function (req, res) {
    // Get the original url, it's a fully qualified path
    var apiPath = req.originalUrl;

    // Form the proxied URL to your java API
    var url = 'https://127.0.0.1' + apiPath;

    // Fire off the request, and pipe the response
    // to the res handler
    request.get(url).pipe(res);
  });

如果无法访问api,请确保添加一些错误处理,例如this SO solution

【讨论】:

    【解决方案2】:

    对于代理问题,我的猜测是它将/api/* 保留在 url 中,并且在您的 API 服务中的路由器上不存在。您可以尝试将/api 添加到 API 服务中的路由器,因为它会在发送时保持 url 字符串相同。否则,您可能需要代理并重写 url,以便 API 将请求与路由匹配。

    另外,如果只安装cors 模块并在应用程序中使用呢?我做了类似的事情,并且在没有所有代理项目的情况下运行良好。 https://www.npmjs.com/package/cors

    【讨论】:

      猜你喜欢
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2020-03-23
      • 2012-05-09
      相关资源
      最近更新 更多