Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redirect check and timeout fix #3

Merged
merged 1 commit into from
Mar 26, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,31 @@ httpreq.post('http://posttestserver.com/post.php',{
);


// set max redirects:
httpreq.get('http://scobleizer.com/feed/',{
headers:{
'User-Agent': 'Magnet', //for some reason causes endless redirects on this site...
}},
function (err, res) {
if (err){
console.log(err);
}else{
console.log(res.body);
}
}
);


// set timeout
httpreq.get('http://www.androidpatterns.com/feed', {timeout: (5 * 1000)},
function (err, res) {
if (err){
console.log(err);
}else{
console.log(res.body);
}
}
);



30 changes: 27 additions & 3 deletions httpreq.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ exports.get = function(url, options, callback){
if(moreOptions.allowRedirects === undefined)
moreOptions.allowRedirects = true;

if(moreOptions.maxRedirects === undefined){
moreOptions.maxRedirects = 10;
}

doRequest(moreOptions, callback);
}

Expand Down Expand Up @@ -88,6 +92,10 @@ function doRequest(o, callback){
headers: {}
};

if(!o.redirectCount){
o.redirectCount = 0;
}

if(o.method == 'POST' && o.parameters){
requestoptions['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
Expand Down Expand Up @@ -118,8 +126,13 @@ function doRequest(o, callback){

// check for redirects
if(res.headers.location && o.allowRedirects){
o.url = res.headers.location;
return doRequest(o, callback);
if(o.redirectCount < 10){
o.redirectCount++;
o.url = res.headers.location;
return doRequest(o, callback);
} else {
callback(new Error("Too many redirects"));
}
}

var responsebody = Buffer.concat(chunks);
Expand All @@ -142,8 +155,19 @@ function doRequest(o, callback){
else
request = http.request(requestoptions, requestResponse);

if(o.timeout){
request.setTimeout(o.timeout, function(){
request.timedOut = true;
request.abort();
});
}

request.on('error', function (err) {
callback(err);
if(request.timedOut){
callback(new Error("Request timed out"));
} else {
callback(err);
}
});

if(body)
Expand Down