Search code examples
node.jsreverse-proxyhttp-proxynode-http-proxyhttp-proxy-middleware

how to reverse-proxy a client/user from one server to another using nodejs?


i was looking a for a way to reverse-proxy my application which is running on localhost:7200 to another server running on 10.0.0.1:3000 by using a POST request

apiRoutes.post('/route', function(req, res) {
res.json({ message: 'Done' });
  var tunroute=req.body.address;
  console.log(tunroute);

   //{tunroute contains the address i.e 10.0.0.1:300}

   //{ here is where i want to proxy to server at 10.0.0.1:300 }

});

please help!!


Solution

  • so i found the answer, i used

    http-proxy-middleware

    for reverse proxying client from one server to another

    here is the code for the same.

    var express = require('express');
    var app = express();
    var proxy = require('http-proxy-middleware');
    var methodOverride = require('method-override');
    var target = ['http://www.facebook.com',
                  'http://10.0.0.1:3000',
                  'http://127.0.0.1']
    
      app.use(methodOverride());
    
      app.get('/change',function(req,res){
    
        options = {
                target: target[2],      // target host
                changeOrigin: false,    // needed for virtual hosted sites
                ws: true,               // proxy websockets
            };
        var = exampleProxy = proxy(options);
    
        app.use('/', exampleProxy);
    
        return res.redirect("./");
      });
    
      app.listen(3000);