Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add redirect url to response object #191

Merged
merged 1 commit into from
Jun 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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