我正在尝试在 NodeJS 上使用 Axios 获取以下网址:https://chromewebstore.google.com/detail/bleabhffpgoeopcfeapggnbdlhklbajk
使用 Axios 执行此操作时,我收到 ERR_FR_TOO_MANY_REDIRECTS。 仔细查看错误时,对我来说,这似乎可能是由于重定向 URL 的编码错误造成的,因为最终应该导致 https://chromewebstore.google.com/detail/%E5%85%AD%E7 %9C%81%E5%8F%91%E6%96%87/bleabhffpgoeopcfeapggnbdlhklbajk(如果在浏览器中输入,则带有中文字符)。
我尝试了很多方法,包括使用 Axios 拦截器重新编码 URL,但没有任何效果。
令人惊讶的是,使用curl(curl -L https://chromewebstore.google.com/detail/bleabhffpgoeopcfeapggnbdlhklbajk)或python请求(requests.get('https://chromewebstore.google.com/detail/)时一切正常bleabhffpgoeopcfeapggnbdlhklbajk')。
这是我使用的代码,我尝试对重定向 URL 进行编码以尝试以某种方式解决它(显然更简单的版本不起作用):
const axiosInstance = axios.create({
maxRedirects: 5,
responseType: 'arraybuffer'
});
try {
const response = await axiosInstance.get('https://chromewebstore.google.com/detail/bleabhffpgoeopcfeapggnbdlhklbajk', {
headers: {
'User-Agent': userAgent,
'Content-Type': 'text/html; charset=UTF-8',
'Accept-Language': 'en-US,en;q=0.5'
}
});
return response.data;
} catch (error) {
if (error.response && error.response.status === 302) {
const location = error.response.headers.location;
console.log('Original redirect URL:', location);
// Split the URL into its components
const urlParts = location.split('/');
// Find the index of the "detail" part
const detailIndex = urlParts.findIndex(part => part === 'detail');
if (detailIndex !== -1 && detailIndex + 1 < urlParts.length) {
// Encode the part after "detail"
urlParts[detailIndex + 1] = encodeURIComponent(urlParts[detailIndex + 1]);
// Join the URL parts back together
const modifiedLocation = urlParts.join('/');
console.log('Modified redirect URL:', modifiedLocation);
// Send a new request with the modified URL
const response = await axiosInstance.get(modifiedLocation, {
headers: {
'User-Agent': userAgent,
'Accept-Charset': 'UTF-8',
'Content-Type': 'text/html; charset=UTF-8'
}
});
return response.data;
} else {
throw new Error('Invalid URL format');
}
} else {
throw error;
}
}
}
有什么想法吗?
提前致谢!
这是 undici 实现
fetch
中的一个错误,已通过 https://github.com/nodejs/undici/pull/2971 修复。
Node.js 的最新版本 v22.0.0 不再出现此错误。
>node
Welcome to Node.js v22.0.0.
Type ".help" for more information.
> (await fetch('https://chromewebstore.google.com/detail/bleabhffpgoeopcfeapggnbdlhklbajk')).url
'https://chromewebstore.google.com/detail/%E5%85%AD%E7%9C%81%E5%8F%91%E6%96%87/bleabhffpgoeopcfeapggnbdlhklbajk'