我正在使用node.js,但我觉得这不一定与节点有关 - 无论如何
我在节点中写了一个url shortener,我想点击缩短的url来获取页面标题 - 这在大多数情况下都适用,通常在重定向后正常等等。
但是当我点击gmail.com时,它会进入一个无限重定向循环 - http://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 :(得分:0)
啊好吧,明白了!
我对https的检查就像
var protocol = (urlInfo.protocol == 'https' ? https : http);
但是节点在协议中添加冒号,所以它应该是
var protocol = (urlInfo.protocol == 'https:' ? https : http);
因此,它继续使用http和gmail将重定向到https永远