React-Native fetch call to localhost endpoint is giving Type Error: Network request failed when using https

React-Native fetch call to localhost endpoint is giving Type Error: Network request failed when using https

我在 Android Studio Emulator 上使用 npm run android 在 expo 客户端上有一个反应本机应用程序 运行ning,WebApi 调用以获取当我在 Visual Studio 项目设置上禁用启用 SSL 时,使用 fetch 的数据工作得很好,见下文,这意味着它在 http 端口 54715 上 运行ning,如果你看到箭头标记我取消选中启用 SSL 复选框

我还对 applicationhost.config 文件进行了更改,将我的本地主机指向 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("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 端口上,当我获取网络时 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 我收到 类型错误:网络请求失败,它无法在本地主机上进行 https 调用。

当我取消选中启用 SSL 和 运行 .Net Core 解决方案时,我可以使用 http,但是如何使用本地 https 进行提取调用?

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

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

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

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

所以,http 或 https 即使它在 Android 模拟器上工作,问题又是它如何在你的 iPhone 设备或​​ Android 设备上工作,我的意思是如果您正在使用 Expo Client 应用程序打开您的 React 本机应用程序,现在如何将本地主机 .NET Core WebApi 或本地计算机上的任何其他端点连接到您的移动设备以安装该应用程序 运行ning.

我有一个通用的工作解决方案,适用于各个设备上的模拟器和移动应用程序。

第 1 步:转到 https://ngrok.com/

第二步:注册,您可以使用GitHub账号

第 3 步:如果您有 windows OS,请单击 windows 下载并解压缩文件,您将 查看 .exe,将其复制到您的桌面或您想要的位置。

第 4 步:转到 windows 资源管理器并在您复制的位置打开命令提示符 exe, 运行 dir 检查你所在的位置是否有 ngrok.exe。

第 5 步:运行 ngrok authtoken yourTokenGivenDuringSignUp ,这是您可能需要的一次性东西 要做

第 6 步:运行 ngrok http https://localhost:PortNumber -host-header="localhost:PortNumber",端口号是您的 .NET 核心解决方案所在的端口 运行ning,在项目属性中启用 SSL 我们需要 https工作。

第 7 步:复制 https link 将由 ngrok 创建 https URL 突出显示,如下例所示

现在您可以使用上面的 link 来替换提取 url 以使移动应用程序或模拟器从您的本地代码运行。

注意*** 我们需要 运行 在第 6 步和我们的解决方案中使用 ngrok,而且 url 每次都不一样,所以 运行 第 6 步和 .NET生成新网址并在 React Native 应用程序中使用的核心解决方案。

快乐编码:)