gpt4 book ai didi

node.js - Node 代理 - 从基本的 http 服务器代理 SSL localhost 目标

转载 作者:搜寻专家 更新时间:2023-10-31 22:33:53 24 4
gpt4 key购买 nike

我正在尝试做的事情:

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

我的尝试:

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

我的问题:

UI 正常...但我无法在 :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);
});

最佳答案

您要找的是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 .

关于node.js - Node 代理 - 从基本的 http 服务器代理 SSL localhost 目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41339643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com