如何在本地将Expo GO应用连接到Django Rest Framework后端?
问题描述
用Expo开发React Native应用,通过iOS设备上的Expo Go测试时,无法访问本地运行的Django Rest Framework后端:
- 本地浏览器能正常访问
http://localhost:8000,但RN中用localhost发起fetch请求失败 - 尝试通过
expo-constants获取IP构建请求地址也无效 - 已配置DRF的Corsheaders中间件、给APIView加
@csrf_exempt、将localhost:19000加入CORS白名单,仍报错 - 后端API在Django测试和本地curl请求中正常,仅Expo Go请求失败
报错信息
Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue
测试用fetch代码
let response = await fetch(BACKEND_URL + "/auth/token/obtain/", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, });
尝试过的地址配置
import Constants from "expo-constants"; const { manifest } = Constants; const uri = `http://${manifest.debuggerHost.split(":").shift()}:8000`;
问题原因及解决方法
1. iOS设备的localhost指向问题
iOS设备上的localhost指向设备自身,而非你的开发电脑。即使在同一局域网,设备也无法通过localhost访问电脑上的服务。
- 解决:找到开发电脑在局域网内的IPv4地址(Windows用
ipconfig,Mac/Linux用ifconfig/ip addr show,找Wi-Fi对应的地址,比如192.168.1.100),将BACKEND_URL设为http://192.168.1.100:8000
2. Django服务器绑定地址限制
默认python manage.py runserver只会绑定127.0.0.1,仅限本机访问,局域网设备无法连接。
- 解决:启动Django时绑定所有地址:
python manage.py runserver 0.0.0.0:8000
3. CORS配置遗漏
即使添加了CORS中间件,可能白名单未覆盖Expo Go的请求来源:
- 解决:在Django的
settings.py中补全白名单(仅限开发环境):
CORS_ALLOWED_ORIGINS = [ "http://192.168.1.100:19000", "http://localhost:19000", "exp://192.168.1.100:19000", # 需添加Expo的协议地址 ] # 或临时允许所有来源(开发环境用): CORS_ALLOW_ALL_ORIGINS = True
4. iOS ATS安全限制
iOS默认拦截HTTP请求,即使是局域网内的非HTTPS请求也会被阻止。
- 解决:在Expo项目的
app.json中添加ATS配置:
{ "expo": { "ios": { "infoPlist": { "NSAppTransportSecurity": { "NSAllowsArbitraryLoads": true } } } } }
注意:此配置仅限开发环境,上线必须改用HTTPS。
5. 防火墙/杀毒软件拦截
开发电脑的防火墙可能阻止了局域网设备访问8000端口。
- 解决:临时关闭防火墙/杀毒软件测试,若正常则给8000端口添加防火墙允许规则。
内容的提问来源于stack exchange,提问作者Arham
相关产品推荐
相关产品推荐

