sindresorhus / got

🌐 Human-friendly and powerful HTTP request library for Node.js
MIT License
14.29k stars 935 forks source link

HTTP Status code associated with each redirect #488

Closed Kikobeats closed 6 years ago

Kikobeats commented 6 years ago

Currently redirectUrls expose a collection of each redirect until reach the final URL:

redirectUrls:
   [ 'https://httpbin.org/relative-redirect/5',
     'https://httpbin.org/relative-redirect/4',
     'https://httpbin.org/relative-redirect/3',
     'https://httpbin.org/relative-redirect/2',
     'https://httpbin.org/relative-redirect/1',
     'https://httpbin.org/get' ]

I want to ask if could support a structure similar to that to know the HTTP status code associated with each redirect.

redirectUrls:
   [ [301, 'https://httpbin.org/relative-redirect/5'],
     [301, 'https://httpbin.org/relative-redirect/4'],
     [301, 'https://httpbin.org/relative-redirect/3'],
     [301, 'https://httpbin.org/relative-redirect/2'],
     [301, 'https://httpbin.org/relative-redirect/1'],
     [302, 'https://httpbin.org/get' ]]
szmarczak commented 6 years ago

You can use this API:

.on('redirect', response, nextOptions) redirect event to get the response object of a redirect. The second argument is options for the next request to the redirect location.

Then save HTTP status code for each redirect. If you want more, it could store all the responses, but there's no need. It'd be too bloated.

brandon93s commented 6 years ago

Building upon @szmarczak's suggestion, the following code snippet produces the output you desire:

const redirects = [];
const request = got.get('https://httpbin.org/relative-redirect/5');

request.on('redirect', info => {
    redirects.push([info.statusCode, info.url]);
});

const response = await request;
Kikobeats commented 6 years ago

Thanks! Works like a charm.

scheung38 commented 5 years ago

Hi @brandon93s, How to add Bearer token in this call? as I am using it my my redirect but getting:

 headers:
   { server: 'nginx/1.12.1',
     date: 'Thu, 31 Jan 2019 15:41:50 GMT',
     'content-type': 'application/json',
     'content-length': '15',
     connection: 'close' },
  body: 'No access token' }

as I don't have issue if i use unirest


const unirest = require("unirest");

const req = unirest("POST", "https://xxxxxxx");

req.send({
    "client_id": "xxxxxxxx",
    "client_secret": "xxcxcxcxcxcxxcxcxcxcxcxcxcxcxcxcxcxcxc",
    "audience": "https:/xcxcxcxcxcxcxcxx/",
    "grant_type": "client_credentials"
});

req.end(function (res) {
    if (res.error) throw new Error(res.error);
    console.log("this is res.body : ", res.body);
});

access_token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsI

which returns my expected access token, the longer I can't do this, I am tempted to use unirest instead, only because rest of the team is using got therefore I am using it.