diff --git a/README.md b/README.md index 0236dd14..0fecf371 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,19 @@ const opts = { get.post(opts, function (err, res) {}) ``` +### Specifically disallowing redirects + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com/will-redirect-elsewhere', + followRedirects: false +} +// res.statusCode will be 301, no error thrown +get(opts, function (err, res) {}) +``` + ### OAuth You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create diff --git a/index.js b/index.js index ab881166..a054837b 100644 --- a/index.js +++ b/index.js @@ -45,7 +45,7 @@ function simpleGet (opts, cb) { const protocol = opts.protocol === 'https:' ? https : http // Support http/https urls const req = protocol.request(opts, res => { - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + if (opts.followRedirects !== false && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { opts.url = res.headers.location // Follow 3xx redirects delete opts.headers.host // Discard `host` header on redirect (see #32) res.resume() // Discard response diff --git a/test/redirect.js b/test/redirect.js index 7ebc6b7b..26131a63 100644 --- a/test/redirect.js +++ b/test/redirect.js @@ -59,6 +59,31 @@ test('do not follow redirects', function (t) { }) }) +test('do not follow redirects and do not error', function (t) { + t.plan(4) + + var server = http.createServer(function (req, res) { + t.equal(req.url, '/0', 'visited /0') + + res.statusCode = 301 + res.setHeader('Location', '/1') + res.end() + }) + + server.listen(0, function () { + var port = server.address().port + get({ + url: 'http://localhost:' + port + '/0', + followRedirects: false + }, function (err, res) { + t.ok(!err, 'got no error') + t.equal(res.statusCode, 301, 'status code 301') + t.equal(res.headers.location, '/1', 'redirect location') + server.close() + }) + }) +}) + test('follow redirects (11 is too many)', function (t) { t.plan(12)