要求npm:处理重定向

Max*_*win 2 javascript redirect node.js npm

我想知道是否有人知道如何使用Bitn或部落或Twitter的t.co URL等网站的Request npm处理重定向。例如,如果我有要使用请求npm抓取的网页,而我必须链接到该页面的链接是一个重定向的网址,该网址太短或太短,我该如何处理这些重定向?

我发现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
});
Run Code Online (Sandbox Code Playgroud)

小智 5

首先,您需要使用followAllRedirects:true参数获取最后一个重定向URL。

request('http://t.co/gJ74UfmH4i', {
  method: 'HEAD',
  followAllRedirects: true
}, function(err, response, body) {
  var url = response.request.href
}) 
Run Code Online (Sandbox Code Playgroud)

>

第二部分是使用一些类似于浏览器的标头向最终网址发出请求

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 
})
Run Code Online (Sandbox Code Playgroud)