【发布时间】:2025-12-01 10:40:01
【问题描述】:
我正在使用 node.js,但我觉得这不一定与节点有关 - 无论如何
我正在节点中编写一个 url 缩短器,我想点击缩短的 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);
}
};
是的!
【问题讨论】:
-
如何阻止它无限重定向 - gmail 不断向我发送重定向标头