2011-03-03 98 views
2

我使用Node.js的,但我有一种感觉,这是没有必然的联系,只是节点 - 反正在服务器端的HTTP请求重定向无限

我正在写在节点的URL缩短,我想要达到缩短的网址,以获得页面标题 - 这在大多数情况下,通常遵循重定向,等等。

但是,当我打gmail.com,它进入无限重定向循环 -​​重定向到https://www.google.com/accounds/ServiceLogin?service=mail&passive=true&rm=false&continue=。 ......这又转向自己永远。

我的代码基本上是一样

var http = require('http'), 
https = require('https'), 
URL = require('url'), 
querystring = require('url'); 

var http_client = {}; 

function _makeRequest(url, callback) { 
    var urlInfo = URL.parse(url); 

    var reqUrl = urlInfo.pathname || '/'; 
    reqUrl += urlInfo.search || ''; 
    reqUrl += urlInfo.hash || ''; 

    var opts = { 
    host: urlInfo.hostname, 
    port: urlInfo.port || (urlInfo.protocol == 'https' ? 443 : 80), 
    path = reqUrl, 
    method: 'GET' 
    }; 

    var protocol = (urlInfo.protocol == 'https' ? https : http); 

    var req = protocol.request(opts, function(res) { 
     var content = ''; 
     res.setEncoding('utf8'); 
     res.addListener('data', function(chunk) { 
     content += chunk; 
     }); 
     res.addListener('end', function() { 
      _requestReceived(content, res.headers, callback); 
     }); 
    }); 

    req.end(); 
}; 

function _requestReceived(content, headers, callback) { 
    var redirect = false; 

    if(headers.location) { 
    newLocation = headers.location 
    redirect = true; 
    } 
    if(redirect) { 
    console.log('redirecting to :'+newLocation); 
    _makeRequest(newLocation, callback) 
    } else { 
    callback(null, content); 
    } 
}; 

没错!

+0

你的问题是什么? – dhofstet 2011-03-04 05:54:40

+0

如何阻止它无限重定向 - gmail不断向我发送重定向标头 – Lowgain 2011-03-05 21:25:35

回答

0

啊好吧,明白了!

我对HTTPS检查就像

var protocol = (urlInfo.protocol == 'https' ? https : http); 

但节点增加了一个冒号的协议,所以它应该是

var protocol = (urlInfo.protocol == 'https:' ? https : http); 

正因为如此它一直使用HTTP和Gmail将重定向是to https forever