发送GET请求遭CORS阻碍,请求失败且无法排查原因
解决Fetch请求失败(TypeError: Failed to fetch)的方案
以下是针对你遇到的问题的排查和解决步骤:
1. 处理CORS跨域限制
浏览器的同源策略会阻止前端直接向外部域名发起请求,这是这类报错最常见的原因。espncricinfo大概率未配置允许你当前域名的CORS响应头,导致请求被浏览器拦截。
- 解决方法:
搭建简单的后端代理服务器转发请求,比如用Node.js实现:
前端代码修改为请求代理地址:const express = require('express'); const fetch = require('node-fetch'); const app = express(); const port = 3000; app.get('/proxy-stats', async (req, res) => { try { const targetUrl = 'https://stats.espncricinfo.com/ci/engine/stats/index.html?class=2;host=6;opposition=5;team=6;template=results;type=batting'; const response = await fetch(targetUrl); const data = await response.text(); res.send(data); } catch (err) { res.status(500).send(err.message); } }); app.listen(port, () => { console.log(`代理服务运行在 http://localhost:${port}`); });;(async () => { try { const response = await fetch('http://localhost:3000/proxy-stats', { method: 'GET', }) console.log(response) } catch (error) { console.log(error) } })()
2. 添加模拟浏览器的请求头
部分网站会校验请求头,识别非浏览器请求并拒绝。可以在fetch中补充常见的浏览器请求头:
;(async () => { try { const response = await fetch('https://stats.espncricinfo.com/ci/engine/stats/index.html?class=2;host=6;opposition=5;team=6;template=results;type=batting', { method: 'GET', headers: { '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', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5' } }) console.log(response) } catch (error) { console.log(error) } })()
3. 应对网站反爬机制
espncricinfo可能有反爬策略,可尝试:
- 降低请求频率,避免短时间内重复请求
- 从浏览器访问目标页面后,复制页面的Cookie到fetch请求头中,模拟已登录状态
4. 排查网络层面问题
用curl命令测试是否能正常访问目标地址:
curl "https://stats.espncricinfo.com/ci/engine/stats/index.html?class=2;host=6;opposition=5;team=6;template=results;type=batting"
如果curl也失败,说明是本地网络限制(如防火墙、代理配置),需要检查网络设置。
内容的提问来源于stack exchange,提问作者Anay
相关产品推荐
相关产品推荐

