如何避免Chrome开发者工具中运行的脚本出现重定向过多错误
解决Chrome fetch请求重定向次数过多报错的方案
问题原因
Chrome浏览器内置的fetchAPI自动跟随重定向的默认次数上限为20次,你遇到的100次重定向场景远超该限制,因此会抛出net::ERR_TOO_MANY_REDIRECTS错误。该限制为浏览器硬编码规则,无法通过修改调试器配置、开关忽略规则绕过,只能调整脚本逻辑处理。
解决方案
禁用fetch的自动重定向逻辑,手动读取响应头的Location字段跟进重定向跳转,完全绕过浏览器的默认次数限制,代码实现如下:
// 支持自定义最大重定向次数的fetch封装 async function fetchWithUnlimitedRedirects(requestUrl, maxRedirectCount = 100) { let currentUrl = requestUrl; let redirectedTimes = 0; while (redirectedTimes < maxRedirectCount) { const response = await fetch(currentUrl, { redirect: "manual", // 核心配置:禁用自动重定向 credentials: "include" // 若请求需要携带Cookie、登录态凭证保留该配置,无需要可删除 }); // 判断是否为重定向响应 if (response.status >= 300 && response.status < 400) { const nextJumpUrl = response.headers.get("Location"); if (!nextJumpUrl) break; // 兼容相对路径的重定向地址 currentUrl = new URL(nextJumpUrl, currentUrl).href; redirectedTimes++; console.log(`第${redirectedTimes}次重定向,目标地址:${currentUrl}`); } else { console.log(`重定向完成,累计跳转${redirectedTimes}次`); return response; } } throw new Error(`已达到设定的最大重定向次数:${maxRedirectCount}`); } // 调用示例 fetchWithUnlimitedRedirects("https://www.not-my-website.com/page-1/", 100) .then(finalResponse => finalResponse.text()) .then(responseContent => console.log("最终响应内容:", responseContent)) .catch(error => console.error("请求异常:", error));
注意事项
- 如果运行脚本时出现CORS跨域错误,需要保证你运行脚本的标签页域名和请求的目标域名一致,否则跨域限制会阻止请求读取响应头信息。
- 若目标站点有反爬、请求频率限制,可以在每次重定向跳转前加
await new Promise(resolve => setTimeout(resolve, 100))来降低请求频率。
内容的提问来源于stack exchange,提问作者Andrei
相关产品推荐
相关产品推荐

