节点代理 – 从基本http服务器代理一个SSL本地主机目标
我在做什么:
代理一个运行在https://127.0.0.1:443/api/
上的java api,沿着我的UI在非SSL http://127.0.0.1:1337/上运行,以便环绕一些CORS问题。
我的尝试:
- 将SSL端口443处的api代理到1338的非SSL开发端口。
- 代理我的用户界面到1337年
- 代理1137至
:8080/index.html
和代理1338至:8080/api/
- 从localhost:8080访问我的应用程序
我的问题:
用户界面进来就好了…但我不能击中API :8080/api/httpSession/init
是的,我仍然可以通过https://localhost/api/httpSession/init
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); });
你要找的是要求pipe道 。 试试这个例子:
// 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,请确保添加一些error handling,例如这个SO解决scheme 。
对于代理问题,我的猜测是它保留/api/*
在url中,并且不存在于您的API服务中的路由器上。 您可以尝试在API服务中添加/api
到路由器,因为它将在发送它时保持urlstring不变。 否则,您可能需要代理并重写url,以便API将请求匹配到路由。
在另一个说明,如何安装cors
模块,并在应用程序中使用? 我做了类似的事情,没有所有的代理项目,它运行良好。 https://www.npmjs.com/package/cors