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

React Native Expo如何调用带自签名证书的本地API?

Expo React Native模拟器调用自签名HTTPS API失败的解决办法

核心原因

Expo默认会严格校验SSL证书,自签名证书不在系统信任列表内,即使你在Android模拟器安装了CA证书,也可能因为Expo的网络栈机制无法识别,导致fetch请求失败。另外你的代码里fetch调用存在语法错误,也可能是问题诱因。

先修正代码中的fetch语法错误

你提供的fetch调用参数格式有误,正确写法如下:

// Android URL
let url = `https://10.0.2.2:44387/api/auth/authpolicy/hasaccess`
let headers = {
        'Content-Type': 'application/json',
        'Authorization': `${tokenType} ${accessToken}`
    }
// 修正method字段的写法
let response = await fetch(url, { 
  method: 'GET', 
  headers: headers 
})

if (!response.ok) {
    throw new Error('Something went wrong getting Client Service Line Access Authorization')
}

方案1:开发环境临时禁用SSL校验(仅开发用)

适合快速调试,在项目根目录的app.json或app.config.js中添加配置:

{
  "expo": {
    // 保留原有配置
    "extra": {
      "fetch": {
        "disableTrustManager": true
      }
    }
  }
}

配置完成后重启Expo服务和模拟器,fetch会跳过SSL证书校验,即可正常调用自签名API。注意:生产环境绝对不能用这个配置。

方案2:让Expo信任你的自签名证书

如果不想完全禁用校验,可以将自签名CA证书导入项目,配置Expo信任该证书:

  1. 将你的自签名CA证书(比如custom-ca.pem)放到项目的assets目录下
  2. 在app.config.js中添加Android网络安全配置:
export default {
  expo: {
    // 原有配置...
    android: {
      networkSecurityConfig: {
        domainConfigs: [
          {
            domain: "10.0.2.2",
            includeSubdomains: true,
            trustAnchors: [
              {
                asset: "./assets/custom-ca.pem"
              }
            ]
          }
        ]
      }
    }
  }
};

iOS端可通过ios.infoPlist添加NSAppTransportSecurity例外,允许指定域名的自签名证书:

export default {
  expo: {
    // 原有配置...
    ios: {
      infoPlist: {
        NSAppTransportSecurity: {
          NSExceptionDomains: {
            "10.0.2.2": {
              NSIncludesSubdomains: true,
              NSExceptionAllowsInsecureHTTPLoads: false,
              NSExceptionRequiresForwardSecrecy: false,
              NSExceptionMinimumTLSVersion: "TLSv1.0",
              NSThirdPartyExceptionAllowsInsecureHTTPLoads: true
            }
          }
        }
      }
    }
  }
};

补充提示

  • 模拟器浏览器能访问但提示证书无效,是因为浏览器允许手动信任证书,但React Native的fetch基于独立网络栈,和浏览器信任机制不同,所以单独安装CA证书无法解决问题。
  • 上线前务必替换为正规CA签发的SSL证书,保障数据安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:25:51