【问题标题】:node.js request get redirect chainnode.js 请求获取重定向链
【发布时间】:2019-01-18 14:09:10
【问题描述】:
是否可以使用request 模块来查看整个重定向链,就像puppeteer 是如何做到的?
我希望能够查看每个状态代码/网址/访问网站时发生的重定向次数
例如,如果我请求“http://apple.com”
url 设置为重定向到
https://www.apple.com(本例中链为1)
我想知道 (1) 发生了重定向以及 (2) 需要多少次重定向才能到达该位置
如果 request 无法做到这一点,是否还有其他库? (我不再使用puppeteer,因为puppeteer 不适用于测试附件)
【问题讨论】:
标签:
node.js
redirect
request
http-redirect
【解决方案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
});
【解决方案2】:
不仅可以,而且使用起来更方便:
重定向对象: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
}
}
)