Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js request get redirect chain

Is it possible to use the request module to look at the entire redirect chain, like how puppeteer does it?

I'd like to be able to see each of the status codes / urls / how many redirects happen when I go a site

for example, if i request 'http://apple.com' the url is set up to redirect to

https://www.apple.com (in this case, the chain is 1) I'd like to know that (1) that redirect happened and (2) how many redirects it took to get to that

If this isn't possible with request, are there any other libraries? (I'm not using puppeteer anymore because puppeteer doesn't work well with testing attachments)

like image 449
User9123 Avatar asked Oct 23 '25 16:10

User9123


2 Answers

Not only is it possible, it can be even easier to use:

Redirect Object: https://github.com/request/request/blob/master/lib/redirect.js

request.get (
      {
        uri: `http://somesite.com/somepage`,
        followAllRedirects: true
      },
      (err, res, body) => {
        if (err) {
          // there's an error
        }
        if (!res) {
          // there isn't a response
        }

        if (res) {
            const status = res.statusCode; // 404 , 200, 301, etc
            const chain = res.request._redirect.redirects; // each redirect has some info too, see the redirect link above
            const contentType = res.headers["content-type"] // yep, you can do this too
        }
    }
)
like image 54
Ronak Shah Avatar answered Oct 25 '25 04:10

Ronak Shah


Figured it out, yes, it is completely possible.

const request = require('request')

request.get({
    uri: 'http://apple.com',
    followAllRedirects: true
}, function (err, res, body) {
    console.log(res.request._redirect.redirectsFollowed)
    console.log(res.request._redirect.redirects) // this gives the full chain of redirects


});
like image 34
User9123 Avatar answered Oct 25 '25 04:10

User9123