我想知道是否有人知道如何使用来自诸如bitly或tribal或Twitter的t.co URL等网站的请求npm来处理重定向。例如,如果我有网页,我想要使用请求npm和我必须访问该页面的链接是一个将重定向我的bity或缩短的URL,我该如何处理这些重定向?
我发现请求npm有一个" followRedirect"默认情况下,options设置为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
});
答案 0 :(得分:4)
首先,您需要使用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
})
答案 1 :(得分:2)
Request package默认情况下遵循HTTP 3xx重定向,但您使用的URL返回的是具有META REFRESH样式重定向的HTTP 200。我不确定Request是否支持这种特定的重定向方式,因此您可能需要解析响应并手动关注它。
GET http://t.co/gJ74UfmH4i HTTP/1.1
HTTP/1.1 200 OK
cache-control: private,max-age=300
content-length: 208
content-type: text/html; charset=utf-8
date: Fri, 28 Aug 2015 16:28:59 GMT
expires: Fri, 28 Aug 2015 16:33:59 GMT
server: tsa_b
set-cookie: muc=b0a729d6-9a30-466c-9cd9-57306369613f; Expires=Wed, 09 Aug 2017 16:28:59 GMT; Domain=t.co
x-connection-hash: 28133ba91da8c83d45afa434e12f8a72
x-response-time: 9
x-xss-protection: 1; mode=block
<noscript><META http-equiv="refresh" content="0;URL=http://nyti.ms/1EmZJhP"></noscript><title>http://nyti.ms/1EmZJhP</title><script>window.opener = null; location.replace("http:\/\/nyti.ms\/1EmZJhP")</script>
理解问题的一个可能途径是使用followRedirect函数来查看是否可以找到它失败的位置。
来自README:
followRedirect
- 将HTTP 3xx响应作为重定向(默认值:true
)。 此属性也可以实现为将响应对象作为单个参数获取的函数,如果重定向应该继续,则应返回true
,否则返回false
。