You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何运行React Native从Django后端获取数据并解决连接问题?

问题

用Django搭建后端,React Native开发前端,Android Studio中配置了Pixel 2 XL模拟器。原本后端执行python manage.py runserver、前端执行expo start均能正常运行,现在要实现React Native从后端获取数据,将后端启动命令改为python manage.py runserver 192.168.1.68:19000,并配置Django的settings文件如下:

INSTALLED_APPS = [
    'corsheaders',
    'DierenWelzijnAdmin.apps.DierenwelzijnadminConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ALLOWED_HOSTS = ['192.168.1.68', '127.0.0.1', ]

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
    "http://localhost:8081",
    "http://localhost:19006",
    "http://localhost:19002",
    "http://192.168.1.69:8000",
    "http://192.168.1.68:19000",
]

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]

同时编写了React Native的请求服务:

export const fetchCategoryData = async () => {
    try {
        const response = await fetch("http://192.168.1.68:19000/animal/categories/main_groups/", {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            throw new Error("Network response was not ok");
        }

        return await response.json();
        //setCategoryData(data);
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

但执行expo start启动React Native应用后,按r重载时出现警告:

warn No apps connected. Sending "reload" to all React Native apps failed. Make sure your app is running in the simulator or on a phone connected via USB.

使用adb devices命令可看到模拟器emulator-5554已连接,且已多次清除模拟器数据,需解决如何让React Native正常运行并成功从后端获取数据的问题。


解决方案

1. 修复Expo与模拟器的连接

  • 启动模拟器后,在Expo终端中按a(对应Android平台),让Expo自动将应用安装并启动到模拟器中,避免手动打开模拟器内的Expo Go再扫码。
  • 若仍无法连接,执行端口转发命令:adb reverse tcp:19000 tcp:19000,将电脑的19000端口映射到模拟器,确保Expo与模拟器的通信链路正常。

2. 调整后端端口与CORS配置

  • 后端使用19000端口会与Expo默认端口冲突,建议更换为其他端口(如8000),启动命令改为:python manage.py runserver 192.168.1.68:8000
  • 同步更新Django的CORS配置:将http://192.168.1.68:8000加入CORS_ORIGIN_WHITELIST,同时修改React Native请求地址为http://192.168.1.68:8000/animal/categories/main_groups/
  • 确认corsheaders.middleware.CorsMiddleware在django.middleware.common.CommonMiddleware之前,当前配置已符合要求,无需调整。

3. 验证模拟器网络连通性

  • 确保模拟器与电脑处于同一局域网,在模拟器内打开浏览器,输入后端地址(如http://192.168.1.68:8000),验证是否能正常访问后端页面。
  • 若无法访问,检查电脑防火墙设置,允许后端端口(如8000)通过防火墙。

4. 调试React Native请求

  • 在fetchCategoryData函数中添加日志,打印请求地址、错误详情,确认请求是否正常发送以及具体错误类型(网络不通/CORS问题等)。
  • 打开React Native调试菜单(按Ctrl+M),选择Debug Remote JS,通过Network面板查看请求状态,精准定位问题。

内容的提问来源于stack exchange,提问作者mightycode Newton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:10:33