【问题标题】:How can I configure app.json to accept all connection types such as HTTP requests?如何配置 app.json 以接受所有连接类型,例如 HTTP 请求?
【发布时间】:2019-08-02 08:04:12
【问题描述】:

在我的 Expo React Native 应用程序中,我一直在尝试从我的 Ruby on Rails API 中获取数据,但似乎不允许使用 http 连接。

我找到的所有解决方案要么将配置添加到 Android 中的 AndroidManifest.xml 和 iOS 中的 Info.plist,我无法访问,但我宁愿在 Expo 中继续开发而不是退出。我已经尝试将localhost 更改为127.0.0.110.0.2.2 以及我机器的IP,但没有一个起作用。我查看了 configuration with app.jsonnetworking 的文档,但我找不到任何关于在 Expo 中配置应用程序传输安全性的信息。我目前正在 android 9.0 Pie 上运行 Expo。

fetch(`http://localhost:3000/api/v1/trainers`, {
    headers: { 
    Accept: 'application/json',
    "Content-Type": "application/json" 
},
}).then(res => res.json())
.catch(err => console.log(err));
TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (420454d9-7271-44d5-b…-3a968d130699:48065)
    at XMLHttpRequest.dispatchEvent (420454d9-7271-44d5-b…-3a968d130699:53513)
    at XMLHttpRequest.setReadyState (420454d9-7271-44d5-b…-3a968d130699:52368)
    at XMLHttpRequest.__didCompleteResponse (420454d9-7271-44d5-b…-3a968d130699:52195)
    at 420454d9-7271-44d5-b…-3a968d130699:52305
    at RCTDeviceEventEmitter.emit (420454d9-7271-44d5-b…-3a968d130699:22482)
    at MessageQueue.__callFunction (420454d9-7271-44d5-b…-3a968d130699:22097)
    at 420454d9-7271-44d5-b…-3a968d130699:21854
    at MessageQueue.__guard (420454d9-7271-44d5-b…-3a968d130699:22051)
    at MessageQueue.callFunctionReturnFlushedQueue (420454d9-7271-44d5-b…-3a968d130699:21853)

【问题讨论】:

    标签: javascript android react-native expo fetch-api


    【解决方案1】:

    您的 REST api 在哪个域上? 从反应本机应用程序(在模拟器上运行)获取到 node.js/express REST api 时,我遇到了同样的问题。我在 React 中找不到解决方法。

    我找到了使用 ngrok (https://ngrok.com) 的解决方案。它允许您向外部公开特定的本地域:端口。使用这种方法,我能够从我的应用程序获取到我的 REST api。

    需要明确的是,我不确定问题出在 React-Native 端。我怀疑是我的防火墙不允许连接通过。我没有搞乱所有这些设置,而是简单地使用了 ngrok。

    【讨论】:

    • 我的 REST API 在 localhost 上运行,ngrok 正是我所需要的!谢谢!
    • Ngrok 可以工作,但如果您使用免费版本,每次启动 ngrok 时都必须更改端点,这有点烦人。我能想到的唯一其他选择是使用自签名证书并在设备上手动安装 CA
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2020-10-15
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多