Node.js Error: Max redirects exceeded

Node.js Error: Max redirects exceeded

如何忽略带有循环重定向的页面? 我使用这段代码来获取页面:

var libxml = require("libxmljs"),
http = require('follow-redirects').http,
url = require("url");

var request = http.request( { "host": host, "path": URL, "port": 80 }, function( response ) {
        var str = '';
        response.on( 'data', function( chunk ) {
            str += chunk;
        });
        response.on( 'end', function() {
            callback( str, response.statusCode );
        }).on( 'error', function ( err ) {
          console.log( err );
        });
    }).end();

它不会去 'error' 块,我有一个例外:

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: Max redirects exceeded.
    at ClientRequest.cb (/var/parsing/node_modules/follow-redirects/create.js:55:19)
    at ClientRequest.g (events.js:199:16)
    at ClientRequest.emit (events.js:107:17)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:426:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
    at Socket.socketOnData (_http_client.js:317:20)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)

查看您正在使用的包的文档 (https://www.npmjs.com/package/follow-redirects),它看起来只有一个 maxRedirects 选项。直接来自链接页面:

require('follow-redirects').maxRedirects = 10;   // Has global affect (be careful!) 

https.request({
  host: 'bitly.com',
  path: '/UHfDGO',
  maxRedirects: 3   // per request setting 
}, function (res) {/* ... */});

错误是由请求对象而非响应对象引发的,因此您需要向 request;

添加一个(额外的)error 侦听器
var request = http.request(...).on('error', function(err) {
  ...
}).end();