节点代理 - 从基本http服务器代理SSL本地主机目标

Ric*_*oss 6 ssl proxy node.js

我想做什么:

代理一个java api,它运行在https://127.0.0.1:443/api/我的UI上,运行在非SSL http://127.0.0.1:1337/上,以便绕过一些CORS问题.

我的尝试:

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

我的问题:

用户界面很好......但我无法点击API :8080/api/httpSession/init

是的,我仍然可以点击API https://localhost/api/httpSession/init

api.js - Renders index.html at:1337

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);
Run Code Online (Sandbox Code Playgroud)

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);
  });
Run Code Online (Sandbox Code Playgroud)

Jac*_*ade 2

您正在寻找的是请求管道。试试这个例子:

  // 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);
  });
Run Code Online (Sandbox Code Playgroud)

如果无法访问 api,请确保添加一些错误处理,例如此 SO 解决方案