Browse Source

Merge pull request #166 from ruyadorno/disable-follow-redirect-option

Added option to toggle automatic following redirects
node-7
Vsevolod Strukchinsky 9 years ago
parent
commit
82446c9e0f
  1. 9
      index.js
  2. 7
      readme.md
  3. 4
      test/redirects.js

9
index.js

@ -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) {
@ -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;
@ -109,7 +110,7 @@ function asPromise(opts) {
}
}
if (statusCode < 200 || statusCode > 299) {
if (statusCode < 200 || statusCode > limitStatusCode) {
throw new got.HTTPError(statusCode, opts);
}
@ -267,6 +268,10 @@ function normalizeArguments(url, opts) {
};
}
if (opts.followRedirect === undefined) {
opts.followRedirect = true;
}
return opts;
}

7
readme.md

@ -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

4
test/redirects.js

@ -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');
});

Loading…
Cancel
Save