我想知道是否有人知道如何使用 Request npm 处理来自 bitly 或 tribal 或 Twitter 的 t.co URL 等网站的重定向。例如,如果我想使用 Request npm 抓取网页,并且我必须到达该页面的链接是一个将重定向我的小 URL 或缩短的 URL,那么我如何处理这些重定向?
我发现 Request npm 有一个“followRedirect”选项默认设置为 true。如果我将其设置为 false,我可以通过抓取返回的页面来获取该页面将我重定向到的下一个链接,但这不是最好的,因为我不知道我需要进行多少次重定向通过。
现在我收到 500 错误。当我将“followRedirect”设置为 true 时。当我将“followRedirect”设置为 false 时,我可以获得每个重定向页面。同样,我不知道我需要经过多少个重定向页面。代码如下:
var options = {
followRedirect: false
};
request('http://t.co/gJ74UfmH4i', options, function(err, response, body){
// when options are set I get the redirect page
// when options are not set I get a 500
});
首先,你需要获取最后一个重定向url,使用followAllRedirects: true参数
request('http://t.co/gJ74UfmH4i', {
method: 'HEAD',
followAllRedirects: true
}, function(err, response, body) {
var url = response.request.href
})
>
第二部分是向最终网址发出请求,并带有一些类似浏览器的标头
request(url, {
headers: {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.46 Safari/537.36"
},
}, function(err, response, body) {
//here is your body
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)