我想知道是否有人知道如何使用 Request npm 处理来自 bitly 或 tribal 或 Twitter 的 t.co URL 等网站的重定向。例如,如果我有一个网页,我想使用 Request npm 抓取,而我必须到达该页面的链接是一个短的或缩短的 URL,它将重定向我,我该如何处理这些重定向?
我发现 Request npm 有一个默认设置为 true 的“followRedirect”选项。如果我将其设置为 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
})
>
第二部分是向最终 url 发出请求,带有一些类似浏览器的 header
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
})
关于javascript - 请求 npm : Handling Redirects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32275621/