如何在 expo 中禁用 https-only fetch 请求 react native/node js

Posted

技术标签:

【中文标题】如何在 expo 中禁用 https-only fetch 请求 react native/node js【英文标题】:How to disable https-only fetch requests in expo react native/node js 【发布时间】:2020-07-01 18:08:14 【问题描述】:

我尝试使用 fetch API 与本地主机上的服务器通信,获取请求会引发以下错误:

[Unhandled promise rejection: TypeError: Network request failed]
- node_modules\whatwg-fetch\dist\fetch.umd.js:473:29 in xhr.onerror
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

我已经读到 ios 只支持 https 请求,即使我之前能够做到这一点,唯一的区别是我使用的是 xampp/mysql,而现在我使用的是带有 mongoose 的 nodejs。

我只是在前端使用下面的

          fetch("http://localhost:3000/user/login", 
            method: "POST",
            headers: 
              "Content-Type": "application/json"
            ,
            body: JSON.stringify(data)
          )
            .then(response => response.json())
            .then(data => 
              console.log("Success:", data);
              console.log("Success");
            )
            .catch(error => 
              console.log(error);
            );

服务器工作正常,我可以正常发布数据并使用邮递员成功登录。 (使用 JSON) 我也试过只输入一个随机的谷歌 url (https://google.com),它返回了一个可读的错误,这是支持 https 问题的逻辑。

有什么建议吗?

编辑: 看来这与iphone和ssl无关,我已经安装了一个android模拟器(Pixel XL,R Software),模拟器没有到达我的本地主机,我也尝试过使用我电脑的本地ip。

我不知道为什么它不与服务器通信,是一些 expo 配置吗?

【问题讨论】:

【参考方案1】:

尝试使用您的 ip 地址作为 baseUrl:类似于“https://192.XXX.X.XX:3000”

要从终端运行ifconfig,它就会出现。

【讨论】:

【参考方案2】:

您可以在本地 Web 服务器上设置自签名证书,请参阅:https://shellcreeper.com/how-to-create-valid-ssl-in-localhost-for-xampp/ 或者您可以在 Google 上搜索类似于“在 localhost 上设置自签名证书”的其他术语。

【讨论】:

我刚刚添加了一个ssl,它没有解决问题,我不确定发生了什么..

以上是关于如何在 expo 中禁用 https-only fetch 请求 react native/node js的主要内容,如果未能解决你的问题,请参考以下文章

HTTPS-Only标准:美国所有政府网站将使用HTTPS加密

在 iOS 模拟器中禁用调试选项卡 [重复]

React Native Expo 更改默认 LAN IP

升级 Expo CLI 有未知错误 --assetPlugins

如何在 Expo 和 NativeBase 中调整状态栏

如何在 React Native / Expo 中请求权限?