React-Native fetch,网络请求失败.不使用localhost

Ata*_*adi 30 javascript fetch ios reactjs react-native

我有一个应用程序,我使用提取来验证用户.它在几天前工作,我没有改变任何东西.刚刚从0.27升级到0.28,没有提取不起作用.

我搜索了将近2天,我已经阅读了stackoverflow中的几乎所有问题.大多数用户试图从localhost获取内容,当他们将其更改为实际的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();
Run Code Online (Sandbox Code Playgroud)

我试图制作一些新项目,简单,只是使用一个简单的fetch示例来教程,它给出了同样的错误.我试图打开我的网站,我试图连接到它,通过模拟器中的浏览器,它的工作原理,但似乎通过我,应用程序无法连接到任何网站/ 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)
Run Code Online (Sandbox Code Playgroud)

实际上我在这里遇到与此用户相同的问题:React-native网络请求总是失败

更新: 来自xcode的info.plist

任何帮助将不胜感激!

Ahm*_*que 61

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

看起来问题出现在React Native 0.28中.解决方案是在React创建的ios> build文件夹中的info.plist文件中"允许任意加载".

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

允许任意负载

  • @Carlos你在Android上解决了这个问题吗?我在RN 0.35,Android API 21上遇到了同样的问题 (7认同)
  • 安卓怎么样?我也面临同样的问题. (3认同)
  • @BenYee:我用我的IP地址替换了localhost并开始正常工作 (2认同)