Browse Source

Added option to toggle automatic following redirects

v5.x
Ruy Adorno 9 years ago
committed by Vsevolod Strukchinsky
parent
commit
fc57c70835
  1. 12
      index.js
  2. 10
      readme.md
  3. 4
      test/redirects.js

12
index.js

@ -36,7 +36,7 @@ function requestAsEventEmitter(opts) {
var req = fn.request(opts, function (res) {
var 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) {
@ -96,13 +96,14 @@ function asCallback(opts, cb) {
ee.on('response', function (res) {
readAllStream(res, opts.encoding, function (err, data) {
var statusCode = res.statusCode;
var limitStatusCode = opts.followRedirect ? 299 : 399;
if (err) {
cb(new got.ReadError(err, opts), null, res);
return;
}
if (statusCode < 200 || statusCode > 299) {
if (statusCode < 200 || statusCode > limitStatusCode) {
err = new got.HTTPError(statusCode, opts);
}
@ -183,10 +184,11 @@ function asStream(opts) {
ee.on('response', function (res) {
var statusCode = res.statusCode;
var limitStatusCode = opts.followRedirect ? 299 : 399;
res.pipe(output);
if (statusCode < 200 || statusCode > 299) {
if (statusCode < 200 || statusCode > limitStatusCode) {
proxy.emit('error', new got.HTTPError(statusCode, opts), null, res);
return;
}
@ -286,6 +288,10 @@ function normalizeArguments(url, opts) {
};
}
if (opts.followRedirect === undefined) {
opts.followRedirect = true;
}
return opts;
}

10
readme.md

@ -135,7 +135,17 @@ Function to be called when error or data are received. If omitted, a promise wil
`Error` object with HTTP status code as `statusCode` property.
<<<<<<< HEAD
###### data
=======
###### followRedirect
Type: `boolean`
Default: `true`
Defines if redirect responses should be followed automatically.
>>>>>>> b3cd961... Added option to toggle automatic following redirects
The data you requested.

4
test/redirects.js

@ -46,6 +46,10 @@ test('follows redirect', async t => {
t.is((await got(`${s.url}/finite`)).body, 'reached');
});
test('does not follow redirect when disabled', async t => {
t.is((await got(`${s.url}/finite`, {followRedirect: false})).statusCode, 302);
});
test('relative redirect works', async t => {
t.is((await got(`${s.url}/relative`)).body, 'reached');
});

Loading…
Cancel
Save