diff --git a/index.js b/index.js index ee648e1..6796d42 100644 --- a/index.js +++ b/index.js @@ -25,6 +25,7 @@ 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; @@ -32,6 +33,10 @@ function requestAsEventEmitter(opts) { 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(); @@ -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); diff --git a/readme.md b/readme.md index c6f2e2c..8322be7 100644 --- a/readme.md +++ b/readme.md @@ -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 diff --git a/test/redirects.js b/test/redirects.js index d12bb24..3d12cdf 100644 --- a/test/redirects.js +++ b/test/redirects.js @@ -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();