Skip to content

Instantly share code, notes, and snippets.

@coderberry
Created August 15, 2014 14:21
Show Gist options
  • Save coderberry/f68004c5f64a16b272df to your computer and use it in GitHub Desktop.
Save coderberry/f68004c5f64a16b272df to your computer and use it in GitHub Desktop.
Proxy express app which allows passthrough requests (in order to maintain static IP)
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // allows parsing of post params
var request = require('request'); // enable performing http requests
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', app.router);
var port = process.env.PORT || 8080; // set our port
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.post('/proxy', function(req, res) {
var params = req.body,
url = req.body.url,
method = req.body.method || 'POST';
method = method.toUpperCase();
// ensure we have a URL to get/post to
if (!url) { return res.json({ error: 'missing url' }) };
delete params.url;
delete params.method;
var headers = {
'User-Agent': 'request',
'Content-Type': 'application/x-www-form-urlencoded'
};
var options = {
url: url,
method: 'GET',
headers: headers,
qs: params
};
if (method === 'POST') {
options = {
url: url,
method: 'POST',
headers: headers,
form: params
}
}
request(options, function(error, response, body) {
res.json({
status: response.statusCode,
body: body,
error: error
});
});
});
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment