Last active
November 9, 2017 13:45
-
-
Save nkurapati/c14025a9af10364b77affe9aaa396f3c to your computer and use it in GitHub Desktop.
Implement Node.js as proxy server. It can handle its own api and can get data from other servers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This proxy handles 2 types are api. | |
1. Local Api: which send data from local server ex: Routes will start with /api/* | |
2. Remote Api: Which takes request from user (frontend/mobile/etc) -> sends it to remote server -> sends response to user. | |
You can use routes starts with your own filter ex: /remote/* | |
*/ | |
var express = require('express'); | |
var httpProxy = require('http-proxy'); | |
var bodyParser = require('body-parser'); | |
var cors = require('cors'); | |
var app = express(); | |
//Root Route | |
app.get('/',function(req,res) { | |
res.send("Server is running, Please contact admin to access api's"); | |
}); | |
//Setup Proxy and Proxy routes | |
// You can divide it into separate module | |
var options = { | |
timeout: 15 * 60 * 1000, | |
target: { | |
host: "www.yourhost.com", | |
port: 8080 | |
}, | |
proxyTimeout: 15 * 60 * 1000 | |
} | |
var proxy = httpProxy.createProxyServer(options); | |
proxy.on('proxyReq', function(proxyReq, req, res, options) { | |
//You can check req data | |
}); | |
proxy.on('proxyRes', function (proxyRes, req, res) { | |
//You can do your modifications if you want to add anything to remote server response | |
}); | |
app.all('/remote/*', function(req, res, next) { | |
//You can do your modifications if you want to add anything to remote server request | |
//You can modify headers, req url and etc | |
proxy.web(req, res, next); | |
}); | |
//Add your body parser after your proxy routes, otherwise it will modify request object and it will fall into errors. | |
app.use(bodyParser.json()); // for parsing application/json | |
//Use cors after proxy routes as remote server will have its own cors, if not you can use this for both servers by adding at top | |
app.use(cors()); | |
//Local routes | |
app.use('/api', function(req, res) { | |
res.status(200).send('Working...'); | |
}); | |
app.listen(3000, function() { | |
console.log("Server is running on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment