Skip to content

Commit

Permalink
Adding automatic redirect following.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeal committed May 19, 2010
1 parent e7e37ad commit e66e90d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
10 changes: 9 additions & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function request (options, callback) {
options.uri = url.parse(options.uri);
}
}

options.followRedirect = options.followRedirect ? options.followRedirect : true;
options.method = options.method ? options.method : 'GET';
options.headers = options.headers ? options.headers : {};
if (!options.headers.host) {
Expand Down Expand Up @@ -46,6 +46,14 @@ function request (options, callback) {
buffer += chunk;
})
response.addListener("end", function () {
if (response.statusCode > 299 && response.statusCode < 400 && options.followRedirect && response.headers.location) {
options.uri = response.headers.location;
delete options.client;
if (options.headers) {
delete options.headers.host;
}
request(options, callback);
}
options.client.removeListener("error", clientErrorHandler);
callback(null, response, buffer);
})
Expand Down
6 changes: 5 additions & 1 deletion tests/couch.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ request({uri:'http://mikeal.couchone.com/testjs', method:'POST', body:'{"_id":"'
if (!response.statusCode == 201) {
throw new Error("Wrong status code "+response.statusCode);
}
});
});

request({uri:'http://gmail.com'}, function (error, response, body) {
sys.puts(error)
})

0 comments on commit e66e90d

Please sign in to comment.