Skip to content

Instantly share code, notes, and snippets.

@jrgleason
Created August 1, 2012 04:15
Show Gist options
  • Save jrgleason/3223595 to your computer and use it in GitHub Desktop.
Save jrgleason/3223595 to your computer and use it in GitHub Desktop.
I had a problem with redirections and node.js so I created this wrapper class for handling it.
app.get('/', function(res, req){
getCookie.execute({
function(err,path,cookie){
handleForward(path,cookie,function(cookie){
//done
})
})
})
})
var handleForward = function(path, cookie, callback){
if(path != null || path != undefined){
var parsedUrl = url.parse(path);
sendget.execute(parsedUrl, cookie, function(err, path, cookie){
handleForward(path, cookie, callback)
})
}
else{
callback(cookie);
}
}
var cookies = require("tough-cookie"),
Cookie = cookies.Cookie;
getCookieString=function(entries){
var cookieString = "";
//console.log("Entries:"+entries)
for (var cookieLoc in entries){
var cookie = entries[cookieLoc]
//console.log(cookie.toString())
cookieString = cookieString + cookie.key + "=" + cookie.value + "; "
}
return cookieString.substring(0,cookieString.length-2)
}
exports.numnumnum = function(cookies){
return getCookieString(cookies)
}
exports.mmmCookies = function (setCookie){
if (setCookie instanceof Array)
cookies = setCookie.map(Cookie.parse);
else
cookies = [Cookie.parse(setCookie)];
//console.log(cookies)
return cookies;
}
var querystring=require("querystring"),
https = require("https"),
METHOD = 'GET',
cookieMonster = require("./cookieMonster")
exports.execute = function(path, cookies, callback){
console.log(JSON.stringify(path))
var returnPath = null
var post_options = {
host: path.hostname,
port: path.port,
path: path.path,
method: METHOD,
headers:{
cookie:cookieMonster.numnumnum(cookies)
}
}
//console.log(JSON.stringify(post_options))
var post_req = https.request(post_options, function(res) {
res.setEncoding('utf8')
res.body = ''
var cookies = cookieMonster.mmmCookies(res.headers['set-cookie']);
if(res.statusCode == 302){
callback(null, res.headers['location'], cookies)
}
res.on('data', function (chunk) {
res.body += chunk
});
res.on('end', function() {
if(res.statusCode != 302){
//console.log(res.body)
callback(null, null, cookies)
}
})
})
post_req.write("");
post_req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment