Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 节点代理 – 从基本http服务器代理SSL本地主机目标大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想做什么:

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

我的尝试:

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

我的问题:

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

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

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);

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);
  });

解决方法

您要找的是 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/*',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.

大佬总结

以上是大佬教程为你收集整理的node.js – 节点代理 – 从基本http服务器代理SSL本地主机目标全部内容,希望文章能够帮你解决node.js – 节点代理 – 从基本http服务器代理SSL本地主机目标所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。