Browse Source

auto-redirect only on GET and HEAD methods

http2
Vsevolod Strukchinsky 10 years ago
parent
commit
2302a1e6e5
  1. 8
      index.js
  2. 2
      test/test-error.js
  3. 2
      test/test-json.js
  4. 8
      test/test-redirects.js

8
index.js

@ -59,6 +59,8 @@ function got(url, opts, cb) {
opts.method = opts.method || 'POST';
}
opts.method = opts.method || 'GET';
// returns a proxy stream to the response
// if no callback has been provided
if (!cb) {
@ -114,8 +116,8 @@ function got(url, opts, cb) {
proxy.emit('response', res);
}
// redirect
if (statuses.redirect[statusCode] && 'location' in res.headers) {
// auto-redirect only for GET and HEAD methods
if (statuses.redirect[statusCode] && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) {
res.resume(); // Discard response
if (++redirectCount > 10) {
@ -138,7 +140,7 @@ function got(url, opts, cb) {
if (statusCode < 200 || statusCode > 299) {
readAllStream(res, encoding, function (err, data) {
err = new GotError(url + ' response code is ' + statusCode + ' (' + statuses[statusCode] + ')', err);
err = new GotError(opts.method + ' ' + url + ' response code is ' + statusCode + ' (' + statuses[statusCode] + ')', err);
err.code = statusCode;
if (data && json) {

2
test/test-error.js

@ -18,7 +18,7 @@ tape('setup', function (t) {
tape('error message', function (t) {
got(s.url, function (err) {
t.ok(err);
t.equal(err.message, 'http://localhost:6767 response code is 404 (Not Found)');
t.equal(err.message, 'GET http://localhost:6767 response code is 404 (Not Found)');
t.end();
});
});

2
test/test-json.js

@ -69,7 +69,7 @@ tape('json option should catch errors on invalid non-200 responses', function (t
t.ok(err.nested);
t.equal(err.nested.message, 'Unexpected token I');
t.ok(err.nested.nested);
t.equal(err.nested.nested.message, 'http://localhost:6767/non200-invalid response code is 500 (Internal Server Error)');
t.equal(err.nested.nested.message, 'GET http://localhost:6767/non200-invalid response code is 500 (Internal Server Error)');
t.end();
});
});

8
test/test-redirects.js

@ -82,6 +82,14 @@ tape('host+path in options are not breaking redirects', function (t) {
});
});
tape('redirect only GET and HEAD requests', function (t) {
got(s.url + '/relative', {body: 'wow'}, function (err, data) {
t.equal(err.message, 'POST http://localhost:6767/relative response code is 302 (Found)');
t.equal(err.code, 302);
t.end();
});
});
tape('cleanup', function (t) {
s.close();
t.end();

Loading…
Cancel
Save