首页 > 解决方案 > 对 localhost 端点的 React-Native 提取调用给出类型错误:使用 https 时网络请求失败

问题描述

我有一个 react-native 应用程序在使用Android Studio Emulatornpm run android的 expo 客户端上运行,当我在 Visual Studio 项目设置中禁用 Enable SSL 时,使用 fetch 获取数据的 WebApi 调用工作得非常好,见下文,这意味着它在 http 端口54715上运行,如果您看到箭头标记我未选中启用 SSL 复选框

图片

我还在 applicationhost.config 文件中进行了更改,以将我的 localhost 指向 127.0.0.1,这是 10.0.2.2 从 Android 模拟器连接的别名,见下文:

 <bindings>
      <binding protocol="http" bindingInformation="*:54715:127.0.0.1" />
      <binding protocol="http" bindingInformation="*:54715:localhost" />
      <binding protocol="https" bindingInformation="*:44367:127.0.0.1" />
 </bindings>

因此,如果我从 React Native 应用程序进行 fetch 调用,它工作得很好,请参见下面的代码:

fetch("http://10.0.2.2:54715/WeatherForecast/getAllProgramTypes")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

但是当我在项目属性上单击 EnableSSL 时,它将在自认证的 https 端口上运行

https://10.0.2.2:44367/WeatherForecast/getAllProgramTypes

https 在44367端口上运行,当我获取 web api 时:

fetch("https://10.0.2.2:44367/WeatherForecast/getAllProgramTypes")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

现在使用 https 我得到TypeError: Network request failed,它无法在 localhost 上进行 https 调用。

当我取消选中 Enable SSL 并运行 .Net Core 解决方案时,我得到了它与 http 一起使用,但是如何使用本地 https 进行 fetch 调用?

当我查看 Microsoft 文档时,它说绕过证书安全检查,我该如何使用 react-native 代码呢?

https://docs.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services#bypass-the-certificate-security-check

标签: react-native.net-corereact-native-android

解决方案


不幸的是,Ciao 似乎无法绕过 Javascript 中的证书安全检查。可能的解决方案:

  1. 将自签名证书添加到本地计算机上的根证书存储库。
  2. 从Let's Encrypt等免费服务获取有效的签名证书。

推荐阅读