node.js请求获取重定向链

时间:2018-08-11 00:06:15

标签: node.js redirect request http-redirect

是否可以使用request模块来查看整个重定向链,就像puppeteer那样吗?

我希望能够看到每个状态代码/网址/访问网站时发生的重定向次数

例如,如果我请求“ http://apple.com” 网址已设置为重定向到

https://www.apple.com(在这种情况下,链为1) 我想知道(1)发生了重定向,并且(2)达到该重定向需要进行多少次重定向

如果request无法做到这一点,是否还有其他库? (我不再使用puppeteer了,因为puppeteer不能很好地测试附件)

2 个答案:

答案 0 :(得分:1)

弄清楚了,是的,完全有可能。

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


});

答案 1 :(得分:1)

不仅可以,而且使用起来甚至更容易:

重定向对象: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
        }
    }
)