React-Native 获取,网络请求失败。不使用本地主机

React-Native fetch, Network request failed. Not using localhost

我有一个应用程序,我正在使用它来对用户进行身份验证。它一直工作到几天前,我没有改变任何东西。刚从 React 0.27 升级到 0.28,不获取不工作。

找了快2天了,Stack Overflow里面的题我几乎都看完了。大多数用户试图从本地主机获取某些东西,当他们将其更改为实际 IP 地址时,他们就可以正常工作了。 但是我没有从 localhost 获取任何东西,我的代码也可以正常工作。

这是我的代码:

fetch('http://somesite.com/app/connect', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'language':'en-US',
        'Authorization': 'Bearer ' + access_token,
      },
      body: JSON.stringify({
        uid: uid,
        refresh_token: refresh_token,
        token: access_token,
        device: device_id,
        device_name: device_name,
      })
    })
.then((response) => response.json())
.then((responseData) => {
    console.log(JSON.stringify(responseData.body))
})
.catch((err)=> {
  console.log('Some errors occured');
  console.log(err);
})
.done();

我试着做一些新项目,很简单,只是从教程中使用了一个简单的获取示例,它给出了同样的错误。我试图打开我试图连接到它的网站,通过模拟器中的浏览器,它可以工作,但似乎通过我的应用程序无法连接到任何 website/IP。它在 Chrome 控制台中给出了这个错误:

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:28193:8)
    at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:14591:15)
    at XMLHttpRequest.setReadyState (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:29573:6)
    at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:29431:6)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:29506:52
    at RCTDeviceEventEmitter.emit (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:13428:23)
    at MessageQueue.__callFunction (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:11999:23)
    at http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:11906:8
    at guard (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:11857:1)
    at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.ios.bundle?platform=ios&dev=true&hot=true:11905:1)

其实我和这个用户有同样的问题:React-native network request always fails

info.plist 来自 xcode:

你应该看看这个 link:https://github.com/facebook/react-native/issues/8118

看起来问题出现在 React Native 0.28 中。解决方案是在 React 创建的 ios>build 文件夹中找到 info.plist 文件中的 "Allow Arbitrary Loads"。

如果您打开 xcode 中的整个 ios 文件夹,然后打开此 info.plist 文件,您可以创建一个新密钥以允许任意加载,它应该可以解决您的问题。

设置 info.plist 对我也不起作用。尝试在 iOS 上 运行。

此问题是代码试图获取 HTTP 端点而不是 HTTPS,不鼓励这样做。如果您从本地主机服务器获取数据,一个简单的解决方案是通过 Ngrok https 端点公开您的本地主机服务器。

步数:

  1. 从 terminal/cmd 下载 ngrok 和 运行 ngrok http 8081,您应该将 8081 更改为您的本地主机服务端口。

  2. Ngrok 会给你一个 https 转发端点,只需使用它来访问你的本地主机服务器。