Node Proxies - proxy server for the local SSL host from the base http server

What I'm trying to do:

A java api proxy that runs on https://127.0.0.1:443/api/ next to my user interface, which runs on non-SSL http://127.0.0.1:1337/ , to make some travel around the world with CORS.

My attempt:

  • Api proxy on SSL port 443 for my non-SSL development port 1338.
  • proxy my user interface until 1337
  • Proxy 1137 - :8080/index.html and proxy 1338 - :8080/api/
  • Access my application from localhost: 8080

My problem:

The user interface works very well ... but I can't hit the API at :8080/api/httpSession/init

Yes, I can still use the API in https://localhost/api/httpSession/init

api.js - Displays 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 - Proxies 1337 and 1338 in 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); }); 
+6
source share
2 answers

What you are looking for is a connection request . Try this example:

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

Be sure to add some error handling if the api cannot be reached, for example this is an SO solution .

+2
source

As for the proxy server, I assume that it stores /api/* in the URL and is not present on the router in your API service. You can try adding /api to the router in the API service, as it will keep the url string the same when it is sent. Otherwise, you probably need a proxy and rewrite the URL so that the API matches the route request.

On the other hand, how about a simple cors module cors and use in an application? I am doing something similar and it works fine without all proxy elements. https://www.npmjs.com/package/cors

+1
source

Source: https://habr.com/ru/post/1013535/


All Articles