What does the 'maximum redirect' error in fetch-api means?

半世苍凉 提交于 2021-01-29 12:40:54

问题


I am trying to fetch some data from a website but got the following error:

{ FetchError: maximum redirect reached at: <URL>
    at ClientRequest.<anonymous> (C:\Users\Michal\Desktop\argentina\node_modules\node-fetch\lib\index.js:1498:15)
    at ClientRequest.emit (events.js:198:13)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:556:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
    at TLSSocket.socketOnData (_http_client.js:442:20)
    at TLSSocket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at TLSSocket.Readable.push (_stream_readable.js:224:10)
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:94:17)
  message:
   'maximum redirect reached at: <URL>',
  type: 'max-redirect' }

The code is:

const fetch = require("node-fetch");
const asyncFuncAsYouAsked = async () => {
    try {
        const response = await fetch(URL);
        const myJson = await response.json();
        let data = JSON.stringify(myJson);
        fs.writeFileSync('data.json', data);
        console.log(data);
    } catch(e) {
        console.log("EROOOOR:");
        console.dir(e);
    } 
}
 asyncFuncAsYouAsked();

what does the 'maximum redirect reached at:' error means and what is the solution for this problem?


回答1:


Apparently, the page you're requesting is redirecting to another page. Maybe you're requesting via the http protocol and it is redirecting to https, for example.

If not, perhaps you can still acquire the data you're trying to fetch by adjusting the redirect and follow option-settings. Something like:

const fetch = require("node-fetch");
const asyncFuncAsYouAsked = async () => {
    try {
        let options = {};
        options.redirect = "follow";
        options.follow = 20;
        const response = await fetch(URL,options);
        const myJson = await response.json();
        let data = JSON.stringify(myJson);
        fs.writeFileSync('data.json', data);
        console.log(data);
    } catch(e) {
        console.log("EROOOOR:");
        console.dir(e);
    } 
}
 asyncFuncAsYouAsked();


来源:https://stackoverflow.com/questions/58706837/what-does-the-maximum-redirect-error-in-fetch-api-means

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!