Skip to content

Commit

Permalink
Merge pull request #7 from ctate/master
Browse files Browse the repository at this point in the history
Maintain specified headers for redirects
  • Loading branch information
ForbesLindesay committed Jan 19, 2016
2 parents 5866998 + a8e57ce commit 3cbdf04
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ The url as a string (e.g. `http://example.com`). It must be fully qualified and
- `agent` - (default: `false`) controlls keep-alive (see http://nodejs.org/api/http.html#http_http_request_options_callback)
- `followRedirects` - (default: `false`) - if true, redirects are followed (note that this only affects the result in the callback)
- `maxRedirects` - (default: `Infinity`) - limit the number of redirects allowed.
- `allowRedirectHeaders` (default: `null`) - an array of headers allowed for redirects (none if `null`).
- `gzip` (default: `false`) - automatically accept gzip and deflate encodings. This is kept completely transparent to the user.
- `cache` - (default: `null`) - `'memory'` or `'file'` to use the default built in caches or you can pass your own cache implementation.
- `timeout` (default: `false`) - times out if no response is returned within the given number of milliseconds.
Expand Down
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,18 @@ function request(method, url, options, callback) {
// This fixes a problem where a POST to http://example.com
// might result in a GET to http://example.co.uk that includes "content-length"
// as a header
options.headers = {};
var headers = caseless(options.headers), redirectHeaders = {};
if (options.allowRedirectHeaders) {
var headerName, headerValue;
for (var i = 0; i < options.allowRedirectHeaders.length; i++) {
headerName = options.allowRedirectHeaders[i];
headerValue = headers.get(headerName);
if (headerValue) {
redirectHeaders[headerName] = headerValue;
}
}
}
options.headers = redirectHeaders;
return request(duplex ? 'GET' : method, resolveUrl(urlString, res.headers.location), options, callback);
} else {
return callback(null, res);
Expand Down
8 changes: 8 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,11 @@ request('GET', CACHED, {cache: 'file'}, function (err, res) {
}, 1000);
});
});

request('GET', 'https://api.github.com/repos/isaacs/npm', {allowRedirectHeaders: ['User-Agent'], followRedirects: true, headers: {'User-Agent': 'http-basic'}}, function (err, res) {
if (err) throw err;

console.log('response I');
assert(res.statusCode === 200);
res.body.resume();
});

0 comments on commit 3cbdf04

Please sign in to comment.