Skip to content

Commit

Permalink
feat: do not follow redirects and do not error out (#44)
Browse files Browse the repository at this point in the history
feat: do not follow redirects and do not error out
  • Loading branch information
feross committed Sep 18, 2019
2 parents 72ecc9f + 8a0215b commit 73508a8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions test/redirect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 73508a8

Please sign in to comment.