React Native使用Fetch调用本地API时出现Network request failed错误
TypeError: Network request failed问题排查 我在Android 7.0实体设备上运行应用时,调用本地服务器API遇到了网络请求失败的错误,具体报错信息如下:
TypeError: Network request failed at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:15823:18) at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17900:39) at XMLHttpRequest.setReadyState (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17655:20) at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17482:16) at blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17592:47 at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:3478:37) at MessageQueue.__callFunction (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2384:44) at blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2154:17 at MessageQueue.__guardSafe (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2346:11) at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2153:14) {stack: TypeError: Network request failed at XMLHttpRe…081/9b6428f5-4e65-45a0-9490-3852c365f0df:2153:14), message: Network request failed}
我的客户端调用代码如下:
const apiURL = "192.168.1.5:3000/api/"; fetch(apiURL + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.props.username, password: this.props.password }) }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); }) .catch((error) => { console.log(error); });
目前已经确认笔记本和手机连接同一WiFi,Manifest文件中也开启了网络权限,但还是找不到问题所在。
我帮你梳理几个最可能导致这个问题的点,你可以按顺序逐个排查:
1. API URL缺少协议头
你当前的apiURL是"192.168.1.5:3000/api/",没有指定http://或者https://协议头。在Android设备上,这种写法会被识别为无效的URL格式,直接触发网络请求失败。
修复方法:给URL补充协议头,修改为:
const apiURL = "http://192.168.1.5:3000/api/";
2. 本地服务器是否允许跨设备访问
确认你的后端服务器是否监听了0.0.0.0或192.168.1.5这个局域网IP,而不是只绑定localhost或127.0.0.1。如果服务器只监听本地回环地址,同一WiFi下的手机是无法访问到的。
举个Node.js/Express的例子,启动服务器时要这样写:
app.listen(3000, '0.0.0.0', () => { console.log('Server running on http://0.0.0.0:3000'); });
3. Android 7.0的明文网络限制
Android 7.0(API 24)及以上系统默认禁止明文HTTP请求,除非你在AndroidManifest.xml中配置了相关权限。
检查方法:在AndroidManifest.xml的<application>标签里添加android:usesCleartextTraffic="true"属性:
<application ... android:usesCleartextTraffic="true">
如果你的服务器用HTTPS就不需要这个配置,但本地测试大多用HTTP,所以这个配置是关键。
4. 防火墙或端口占用问题
检查你的笔记本防火墙是否允许3000端口的入站请求,同时确认3000端口没有被其他程序占用。可以用netstat类工具查看端口状态,确保服务器确实在3000端口正常运行。
5. 手机与笔记本的网络连通性
在手机浏览器中直接访问http://192.168.1.5:3000/api/login(或服务器的其他测试接口),看看能不能正常返回数据。如果浏览器也无法访问,说明是网络层面的问题;如果浏览器能访问,再回头排查代码细节。
按这个顺序排查,应该能很快定位到问题~
内容的提问来源于stack exchange,提问作者PuskarShestha

