React Native API请求失败求助:Uncaught error. Failed to fetch
问题排查与解决方案
针对你遇到的React Native和浏览器中API请求报"Failed to fetch"的问题,结合你的描述给出以下具体排查和解决步骤:
1. 修正localhost访问问题
- React Native场景:模拟器/真机中的
localhost指向设备自身,而非运行后端的电脑。必须替换为电脑的局域网IP地址(Windows用ipconfig、Mac用ifconfig查看),比如http://192.168.1.100:3000/tweet。 - 浏览器场景:如果前端是HTTPS服务(比如
https://localhost:3000),调用HTTP接口会被浏览器安全策略拦截。调试阶段可临时禁用浏览器的混合内容拦截,或把后端改成HTTPS。
2. 完善错误捕获逻辑
原代码未处理网络层面的异常(比如连接超时、域名解析失败),这类错误不会进入res.status判断,会直接抛出导致"Failed to fetch"。修改代码添加try/catch捕获真实错误:
useEffect(() => { const fetchTweets = async() => { try { // 替换为电脑局域网IP const url = 'http://192.168.xxx.xxx:3000/tweet'; const authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbklkIjozNX0.PhYEPigRB0Jpj6uW11-J8roshWrR4rfdfCPiXgS2gig'; const res = await fetch(url, { headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' }, }); if (!res.ok) { const errorData = await res.json(); console.error('API返回错误:', errorData); throw new Error(`请求失败,状态码:${res.status}`); } const data = await res.json(); console.log(data); setTweets(data); } catch (err) { console.error('请求出错详情:', err.message); } }; fetchTweets(); }, []);
3. 验证CORS配置完整性
即使配置了CORS,也可能存在细节遗漏:
- 确认后端允许前端的Origin(比如React Native调试地址
http://localhost:8081、浏览器前端地址http://localhost:3000) - 显式允许
Authorization自定义头(很多CORS默认不开放) - 以Express为例,正确的CORS配置应该类似:
const cors = require('cors'); app.use(cors({ origin: ['http://localhost:8081', 'http://localhost:3000'], allowedHeaders: ['Authorization', 'Content-Type'], methods: ['GET', 'POST', 'PUT', 'DELETE'] }));
4. React Native平台额外配置
- iOS:在
Info.plist中添加ATS例外(调试阶段允许HTTP请求):
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
- Android:确保
AndroidManifest.xml中包含网络权限:
<uses-permission android:name="android.permission.INTERNET" />
先按上述步骤修改,通过控制台打印的具体错误信息,就能定位到问题的核心原因。
内容的提问来源于stack exchange,提问作者Efojensen
相关产品推荐
相关产品推荐

