Skip to content

Commit

Permalink
Add redirect url to response object (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rowno authored and sindresorhus committed Jun 19, 2016
1 parent 9bb4696 commit 52a67e6
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,18 @@ function requestAsEventEmitter(opts) {
const ee = new EventEmitter();
let redirectCount = 0;
let retryCount = 0;
let redirectUrl;

const get = opts => {
const fn = opts.protocol === 'https:' ? https : http;

const req = fn.request(opts, res => {
const statusCode = res.statusCode;

if (redirectUrl) {
res.url = redirectUrl;
}

if (isRedirect(statusCode) && opts.followRedirect && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) {
res.resume();

Expand All @@ -40,7 +45,7 @@ function requestAsEventEmitter(opts) {
return;
}

const redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location);
redirectUrl = urlLib.resolve(urlLib.format(opts), res.headers.location);
const redirectOpts = Object.assign({}, opts, urlLib.parse(redirectUrl));

ee.emit('redirect', res, redirectOpts);
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ It's a `GET` request by default, but can be changed in `options`.

#### got(url, [options])

Returns a Promise, that resolves to `response` object with `body` property.
Returns a Promise, that resolves to `response` object with `body` property and a `url` property (which contains the final URL after redirects).

##### url

Expand Down
5 changes: 5 additions & 0 deletions test/redirects.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ test('redirects works with lowercase method', async t => {
t.is(body, '');
});

test('redirect response contains new url', async t => {
const url = (await got(`${http.url}/finite`)).url;
t.is(url, `${http.url}/`);
});

test.after('cleanup', async () => {
await http.close();
await https.close();
Expand Down

0 comments on commit 52a67e6

Please sign in to comment.