Skip to content

Commit

Permalink
Merge pull request #166 from ruyadorno/disable-follow-redirect-option
Browse files Browse the repository at this point in the history
Added option to toggle automatic following redirects
  • Loading branch information
floatdrop committed Apr 6, 2016
2 parents f335141 + b3cd961 commit 82446c9
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function requestAsEventEmitter(opts) {
const req = fn.request(opts, res => {
const statusCode = res.statusCode;

if (isRedirect(statusCode) && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) {
if (isRedirect(statusCode) && opts.followRedirect && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) {
res.resume();

if (++redirectCount > 10) {
Expand Down Expand Up @@ -98,6 +98,7 @@ function asPromise(opts) {
.catch(err => reject(new got.ReadError(err, opts)))
.then(data => {
const statusCode = res.statusCode;
const limitStatusCode = opts.followRedirect ? 299 : 399;

res.body = data;

Expand All @@ -109,7 +110,7 @@ function asPromise(opts) {
}
}

if (statusCode < 200 || statusCode > 299) {
if (statusCode < 200 || statusCode > limitStatusCode) {
throw new got.HTTPError(statusCode, opts);
}

Expand Down Expand Up @@ -267,6 +268,10 @@ function normalizeArguments(url, opts) {
};
}

if (opts.followRedirect === undefined) {
opts.followRedirect = true;
}

return opts;
}

Expand Down
7 changes: 7 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ Option accepts `function` with `retry` and `error` arguments. Function must retu

**Note:** if `retries` is `number`, `ENOTFOUND` and `ENETUNREACH` error will not be retried (see full list in [`is-retry-allowed`](https://github.com/floatdrop/is-retry-allowed/blob/master/index.js#L12) module).

###### followRedirect

Type: `boolean`
Default: `true`

Defines if redirect responses should be followed automatically.


#### Streams

Expand Down
4 changes: 4 additions & 0 deletions test/redirects.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ test('follows redirect', async t => {
t.is((await got(`${http.url}/finite`)).body, 'reached');
});

test('does not follow redirect when disabled', async t => {
t.is((await got(`${http.url}/finite`, {followRedirect: false})).statusCode, 302);
});

test('relative redirect works', async t => {
t.is((await got(`${http.url}/relative`)).body, 'reached');
});
Expand Down

0 comments on commit 82446c9

Please sign in to comment.