【问题标题】:Request npm: Handling Redirects请求 npm:处理重定向
【发布时间】:2015-11-23 09:14:35
【问题描述】:

我想知道是否有人知道如何使用 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
});

【问题讨论】:

标签: javascript node.js redirect npm


【解决方案1】:

首先需要获取最后一个重定向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 
})

【讨论】:

  • 感谢您的回答!我确实想为其他阅读本文的人注意一件事。此解决方案有效,但我遇到了陷入事件循环以及必须释放事件侦听器的问题。
【解决方案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

【讨论】:

  • 我也发现了。我在文档中发现的是“followRedirect”接受一个必须返回 true 的函数。我想知道它是否可以返回一个真实的值。也许是另一个请求函数。
  • 啊,刚看到这个很抱歉。
猜你喜欢
  • 2018-06-13
  • 1970-01-01
  • 2014-11-20
  • 2020-08-04
  • 1970-01-01
  • 2022-01-05
  • 2016-09-14
  • 2016-02-10
  • 1970-01-01
相关资源
最近更新 更多