node-fetch请求alsa.es触发maximum redirect reached错误求助
解决node-fetch请求alsa.es时的max-redirect错误
报错信息
ERR FetchError { message: 'maximum redirect reached at: https://www.alsa.es/o/Alsa-main-theme/images/web2020/logo-alsa.svg', type: 'max-redirect' }
已知无效的尝试
- 调整node-fetch的
maxRedirect参数 - 修改请求头的
User-Agent
针对性解决建议
手动追踪重定向链
用curl命令查看完整跳转流程,确认是否存在循环重定向或需要特定请求头:curl -v https://www.alsa.es/o/Alsa-main-theme/images/web2020/logo-alsa.svg观察输出里的
Location头和HTTP状态码,定位跳转异常的环节。模拟浏览器完整请求头
复制浏览器访问该URL时的全部请求头(包括Accept、Accept-Encoding、Accept-Language、Referer、Cookie等),在node-fetch中完整设置:const fetch = require('node-fetch'); const headers = { 'Accept': 'image/avif,image/webp,*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Referer': 'https://www.alsa.es/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', // 复制浏览器中的Cookie字段 'Cookie': '...' }; fetch('https://www.alsa.es/o/Alsa-main-theme/images/web2020/logo-alsa.svg', { headers }) .then(res => res.buffer()) .then(data => console.log('获取成功')) .catch(err => console.error(err));手动处理重定向
禁用自动重定向,手动控制每一步跳转,避免循环或异常跳转:const fetch = require('node-fetch'); async function fetchWithManualRedirect(url, headers = {}) { let response = await fetch(url, { redirect: 'manual', headers }); let redirectCount = 0; const maxAllowedRedirects = 10; // 自定义最大跳转次数 while (response.status >= 300 && response.status < 400 && response.headers.get('Location')) { if (redirectCount >= maxAllowedRedirects) { throw new Error('手动跳转次数超出限制'); } const nextUrl = new URL(response.headers.get('Location'), url).href; // 携带上一步的Cookie等头信息 const newHeaders = { ...headers, ...response.headers.raw() }; response = await fetch(nextUrl, { redirect: 'manual', headers: newHeaders }); url = nextUrl; redirectCount++; } return response; } // 调用示例 fetchWithManualRedirect('https://www.alsa.es/o/Alsa-main-theme/images/web2020/logo-alsa.svg') .then(res => res.buffer()) .then(data => console.log('获取成功')) .catch(err => console.error(err));检查地区限制
若curl或手动跳转仍失败,可能网站限制非西班牙IP,尝试使用西班牙地区的代理:const fetch = require('node-fetch'); const proxyUrl = 'http://your-spanish-proxy:port'; fetch('https://www.alsa.es/o/Alsa-main-theme/images/web2020/logo-alsa.svg', { agent: new (require('https-proxy-agent'))(proxyUrl) }) .then(res => res.buffer()) .catch(err => console.error(err));需先安装依赖:
npm install https-proxy-agent
内容的提问来源于stack exchange,提问作者dalvi
相关产品推荐
相关产品推荐

