【问题标题】:React Native network request fails on iPhone but succeeds in iOS simulatorReact Native 网络请求在 iPhone 上失败,但在 iOS 模拟器中成功
【发布时间】:2016-12-31 02:02:37
【问题描述】:

正如许多人在回答类似问题时所建议的那样,我编辑了我的info.plist,添加了:

<key>NSAllowsArbitraryLoads</key>
<true/>

我还确保在 Xcode 中允许任意加载:

在 iOS 模拟器中一切正常,但是当我尝试在我的 iPhone 上发出网络请求时,我在远程调试器中收到此错误:

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (fetch.js:441)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:378)
    at XMLHttpRequest.js:482
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:236)
    at MessageQueue.js:108
    at guard (MessageQueue.js:46)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:107)

我重新启动 Xcode 的次数比我现在数的要多。我从来没有在任何其他应用程序上遇到过这个问题。这里是请求中的代码,错误来自底部第二个catch

loginFinished (error, result) {
  if (error) {
    console.log(error)
    alert("Login failed with error: " + error);
  } else if (result.isCancelled) {
    alert("Login was cancelled");
  } else {
    AccessToken.getCurrentAccessToken()
      .then(response => {
        console.log('1',response)
        fetch(`http://localhost:3000/auth`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            fbAccessToken: response.accessToken
          })
        })
        .then(response => response.json())
        .then(data => {
          console.log('data: ', data)
          this.props.setUser(data)
        })
        //Network error comes from this catch
        .catch(err => console.log(err))
      })
      .catch(err => console.log(err))
  }
}

【问题讨论】:

    标签: ios react-native fetch


    【解决方案1】:

    问题是您正试图通过手机访问localhost。当您在与服务器相同的计算机上运行 iOS 模拟器时,运行良好,但您的手机需要计算机的主机名或 IP 地址。以下是您可以解决此问题的几种方法:

    • 在您的计算机 (ngrok http 3000) 上运行类似 ngrok 的网络隧道,并通过 http://&lt;hash&gt;.ngrok.io 访问它。由于 ngrok 会终止 TLS,因此您也可以测试 HTTPS URL。
    • 找到您计算机的主机名并通过http://&lt;hostname&gt;.local:3000 访问它。这需要您的计算机和路由器支持 Bonjour。
    • 找到您计算机的 LAN IP 地址并通过http://&lt;ip&gt;:3000 访问它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多