Skip to content

Instantly share code, notes, and snippets.

@amir-rahnama
Created October 26, 2015 13:34
Show Gist options
  • Save amir-rahnama/4307fa53d7855a5a904e to your computer and use it in GitHub Desktop.
Save amir-rahnama/4307fa53d7855a5a904e to your computer and use it in GitHub Desktop.
Minimal Node.js Proxy Server Module (with Gulp)
var proxy = require('proxy.js')();
proxy.run();
var express = require('express'),
app = express(),
https = require('https'),
request = require('request'),
bodyParser = require('body-parser'),
PROXY_PORT = 12345,
HTTPS_POST = 443,
API_ENDPOINT = '/v3',
CONTENT_TYPE = 'application/json',
HTTPS_HOST = 'sub.domain.com';
var Server = function() {
var init = function() {
try {
app.listen(PROXY_PORT);
} catch (err) {
console.error(err.message);
}
app.use(bodyParser.json());
console.log('EXPRESS.JS SERVER LISTENING ON PORT:', PROXY_PORT)
};
var bind = function() {
app.use(API_ENDPOINT, function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
console.log(new Date(), ' -- Rquest Received:', req.body, req.url);
https_req(req, res, next);
});
};
var https_req = function(req, res, next) {
var options = {
hostname: HTTPS_HOST,
port: HTTPS_POST,
path: API_ENDPOINT + req.url,
method: 'POST',
headers: {
'Content-Type': CONTENT_TYPE
}
},
body = '',
requ = https.request(options, function(https_res) {
console.log(new Date(), 'statusCode: ', https_res.statusCode);
console.log(new Date(), 'headers: ', https_res.headers);
https_res.on('data', function(d) {
body += d;
});
https_res.on('end', function() {
res.send(body);
console.log(new Date(), 'Sent request: ', req.body);
next();
});
});
requ.write(JSON.stringify(req.body));
requ.end();
};
return {
run: function() {
init();
bind();
}
};
};
Server.prototype.run = Server.run;
module.exports = Server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment