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

Expo Go安卓端HTTPS请求失效,HTTP及其他系统正常

解决Expo安卓端HTTPS请求失败问题

问题背景

将环境变量EXPO_PUBLIC_API_URL切换到IP地址的HTTPS服务时,安卓端(包括Expo Go和构建版本)请求失败,但HTTP正常,其他平台无异常。使用版本:EXPO-Version 0.18.26,Expo 51.0.24,react-native ^0.74.3。

请求代码:

try {
  const response = await fetch(
    process.env.EXPO_PUBLIC_API_URL + "/login/create",
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0",
      },
    }
  );

  console.log(response);

  if (!response.ok) {
    throw new Error(`Fetch request failed with status ${response.status}`);
  }

  const data = await response.json();

  setError("received");
  console.log("Data received:", data);

  // Working with the response
} catch (error) {
  console.error("Fehler beim Abrufen der Daten:", error);
}

当前安卓app.json配置:

"android": {
  "adaptiveIcon": {
    "foregroundImage": "./assets/images/icon.png",
    "backgroundColor": "#ffffff"
  },
  "package": "XXX",
  "versionCode": 13,
  "permissions": [
    "INTERNET",
    "ACCESS_NETWORK_STATE"
  ]
},

解决步骤

1. 添加安卓网络安全配置

安卓默认会严格验证HTTPS证书合法性,IP地址的HTTPS服务通常使用自签名证书,系统会拒绝信任。需配置网络安全策略允许该IP的HTTPS请求:

  • 在项目根目录创建路径:android/app/src/main/res/xml/network_security_config.xml(目录不存在则手动创建)
  • 写入以下内容(替换37.XX.XXX.XXX为实际IP):
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="false">
    <domain includeSubdomains="true">37.XX.XXX.XXX</domain>
    <trust-anchors>
      <certificates src="system" />
      <!-- 若使用自签名证书,将证书放入res/raw目录后添加此行 -->
      <!-- <certificates src="@raw/your_certificate" /> -->
    </trust-anchors>
  </domain-config>
  <!-- 调试环境可临时允许信任用户证书,生产环境建议删除 -->
  <!-- <debug-overrides>
    <trust-anchors>
      <certificates src="user" />
    </trust-anchors>
  </debug-overrides> -->
</network-security-config>
  • 在app.json的android字段中添加配置引用:
"android": {
  "adaptiveIcon": {
    "foregroundImage": "./assets/images/icon.png",
    "backgroundColor": "#ffffff"
  },
  "package": "XXX",
  "versionCode": 13,
  "permissions": [
    "INTERNET",
    "ACCESS_NETWORK_STATE"
  ],
  "networkSecurityConfig": "@xml/network_security_config"
},

2. 确认构建配置

  • 若使用EAS Build,确保eas.json中的构建配置未覆盖网络安全设置
  • 重新构建安卓应用:运行eas build -p android(本地构建用expo run:android)

3. 调试错误详情

若问题依旧,在catch块打印更详细的错误信息定位原因:

catch (error) {
  console.error("请求错误详情:", error.message);
  console.error("错误栈:", error.stack);
}

常见失败原因:证书过期、证书域名与IP不匹配、自签名证书未被信任。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:34:59