Browse Source

Add redirect url to response object (#191)

node-7
Roland Warmerdam 8 years ago
committed by Sindre Sorhus
parent
commit
52a67e60a1
  1. 7
      index.js
  2. 2
      readme.md
  3. 5
      test/redirects.js

7
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);

2
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

5
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();

Loading…
Cancel
Save