开发者

infinite redirect on server-side http request

I'm using node.js but I have a feeling this isn't necessarily related to just node - anyway

I'm writing a url s开发者_Go百科hortener in node, and i want to hit the shortened url to get the page title - this works in most cases, usually follows redirects properly, etc.

But when I hit gmail.com, it goes into an infinite redirect loop - http://gmail.com redirects to https://www.google.com/accounds/ServiceLogin?service=mail&passive=true&rm=false&continue=....... which in turn redirects to itself forever.

my code is basically like

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);
  }
};

yep!


ahh okay, got it!

my check for https was like

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

but node adds a colon to the protocol, so it should have been

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

Because of this it kept using http and gmail would redirect be to https forever

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜