harpreetkhalsagtbit / node-proxy-learning

Node Proxy - Middleware using Express and http-proxy-middleware
GNU General Public License v3.0
0 stars 0 forks source link

node-proxy-learning

Express Middleware for Routing various API requests to Different Servers using node http-proxy-middleware package.

Build StatusDependencies

How to use?

  1. clone repo and npm install

  2. cd node-proxy-learning and npm install

  3. Run different servers - node server1, node server2, node server3,

  4. Run proxy-middleware - node app.js

  5. Open Browser(or use curl/ajax etc) and hit URLs

    http://localhost:3000/api/v1/carton

    http://localhost:3000/api/v2/carton

    http://localhost:3000/api/v3/carton

  6. Check Reponse for each Request from different Servers

Tests

npm test

Authenticate and Then Proxy Request

// API ROUTES -------------------
// get an instance of the router for api routes
var apiRoutes = express.Router();

// middleware that is specific to this router
// Authenticate User Before Proxing Request
apiRoutes.use(function timeLog(req, res, next) {
    console.log('Time: ', Date.now());

    // Only If Authorized User
    next();
    // else block Request here
    // res.status(403)        // HTTP status 403: Access Denied
    //    .send('Access Forbidden');
});

var middleStringApi = "/api"
// apply the routes to our application with the prefix /api
app.use(middleStringApi, apiRoutes);

.
.
.
.
.

var options = {
    target: 'http://localhost', // target host 
    changeOrigin: true, // needed for virtual hosted sites 
    ws: true, // proxy websockets 
    pathRewrite: {
    },
    proxyTable: {
    }
};

// create the proxy 
var proxy = proxyMiddleware(middleStringApi, options);

app.use(proxy);