Skip to content

Instantly share code, notes, and snippets.

@vinz243

vinz243/proxy.js Secret

Created October 20, 2014 11:33
Show Gist options
  • Save vinz243/fd01b77ef309101976a5 to your computer and use it in GitHub Desktop.
Save vinz243/fd01b77ef309101976a5 to your computer and use it in GitHub Desktop.
var util = require('util'),
colors = require('colors'),
http = require('http'),
httpProxy = require('http-proxy'),
connect = require('connect')
var welcome = [
'# # ##### ##### ##### ##### ##### #### # # # #',
'# # # # # # # # # # # # # # # # ',
'###### # # # # ##### # # # # # # ## # ',
'# # # # ##### ##### ##### # # ## # ',
'# # # # # # # # # # # # # ',
'# # # # # # # # #### # # # '
].join('\n');
util.puts(welcome.rainbow.bold);
//
// Basic Http Proxy Server
//
proxy = httpProxy.createServer({
target: 'http://anotherserver.com/'
});
timers = {}
proxy.on('proxyReq', function(proxyReq, req, res, options) {
timers[req.method + ' ' + req.url] = Date.now()
proxyReq.setHeader('Host', 'http://anotherserver.com/');
});
proxy.on('error', function(e) {
console.log(e);
});
var cookie = undefined
proxy.on('proxyRes', function(proxyRes, req, res) {
console.log(req.method.green +
' ' + req.url.cyan + ' - ' + (proxyRes.statusCode + "")[((proxyRes.statusCode +
"")[
0] - 0 > 3) ? "red" : "green"] + ' - ' + (Date.now() - timers[req.method +
' ' +
req.url]) +
' ms\t (' + cookie + ')'); // This logs the request
});
connect.createServer(
function(req, res, next) {
res.oldWrite = res.write;
var body = ""
res.write = function(data) {
body = data.toString('UTF8')
cookie = (/<cookie><!\[CDATA\[wenvjgol=(.+)\]\]><\/cookie>/g.exec(
body) || ["", undefined])[1]
res.oldWrite(data);
}
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8100'); // Angular app location
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Headers',
'Content-Type, Authorization');
console.log('setting cookie 2 ')
if (cookie) {
res.setHeader('Set-Cookie', 'wenvjgol=' + cookie +
'; Domain=localhost:8101; Path=/; Expires=' + new Date(Date.now() + // Proxy location
1000 * 3600 * 24).toUTCString())
}
next();
},
function(req, res) {
if (req.method === "OPTIONS") {
res.end();
return;
}
proxy.web(req, res);
}
).listen(8101);
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue +
'8101'.yellow);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment