【问题标题】:infinite redirect on server-side http request服务器端http请求的无限重定向
【发布时间】: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 不断向我发送重定向标头

标签: http redirect node.js


【解决方案1】:

嗯,好的,明白了!

我对 https 的检查就像

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

但是节点在协议中添加了一个冒号,所以它应该是

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

因此它一直使用 http,而 gmail 将永远重定向到 https

【讨论】: