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



我想做什么:

代理一个https://127.0.0.1:443/api/在非 SSL http://127.0.0.1:1337/上运行的 Java api,该 API 与我的 UI 一起运行,以绕过一些 CORS 问题。

我的尝试:

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

我的问题:

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

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

api.js- 渲染索引.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);

开始.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);
});

您要查找的是请求管道。试试这个例子:

// 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,请确保添加一些错误处理,例如此 SO 解决方案。

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

另一方面,仅安装cors模块并在应用程序中使用怎么样?我做了类似的事情,并且在没有所有代理项目的情况下运行良好。https://www.npmjs.com/package/cors

最新更新