axios的网络错误和本机反应

时间:2018-03-19 19:18:18

标签: react-native axios

我使用外部托管的Django python框架创建了一个API端点。我可以从浏览器(mydomain.com/endpoint/)访问我的端点并验证没有错误。当我在我的开发机器(localhost:8000/endpoint/)上本地运行我的测试django服务器时也是如此。当我使用localhost作为端点时,我的json数据没有问题。当我使用我的生产域时,axios会遇到网络错误,并且没有太多的上下文...从调试控制台我得到了这个:

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
    at XMLHttpRequest.js:493
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:353)
    at MessageQueue.js:118
    at MessageQueue.__guardSafe (MessageQueue.js:316)

这是我的反应本机组件中的axios调用:

    componentDidMount() {
        axios.get('mydomain.com/get/').then(response => {  // localhost:8000/get works
            this.setState({foo:response.data});
        }).catch(error => {
            console.log(error);
        });
    }

8 个答案:

答案 0 :(得分:3)

  1. localhost 更改为您的 ip(192.168.43.49)
  2. 添加 http://

    http://192.168.43.49:3000/user/

答案 1 :(得分:2)

似乎默认情况下iOS中未加密的网络请求被阻止,即https将起作用,http则不会。

From the docs

  

默认情况下,iOS会阻止任何未使用SSL加密的请求。   如果您需要从明文URL(以http开头的URL)获取   您首先需要添加App Transport Security例外。

答案 2 :(得分:2)

如果您在其他帖子中没有找到答案

就我而言,我使用 Rails 作为后端,并尝试使用 Axios 向 http://localhost:3000 发出请求,但每次都收到 Network Error 作为响应。然后我发现在android模拟器的情况下我需要向http://10.0.2.2:3000发出请求。对于 iOS 模拟器,它适用于 http://localhost:3000

结论

使用

http://10.0.2.2:3000

代替

http://localhost:3000

答案 3 :(得分:0)

我面临着同样的问题。

我看起来更深,我的

端点url不正确。

通过为axios提供正确的确切网址,我的api就像魅力一样。

希望它可能对任何人都有帮助

答案 4 :(得分:0)

对我来说,问题是因为我的远程URL不正确。 如果您的网址是.env文件,请交叉检查命名并确保 如果以其他方式命名,则以REACT_APP_为前缀的React可能找不到它。

在.env文件中,类似REACT_APP_BACKEND_API_URL = https://appurl/api 可以以const {REACT_APP_BACKEND_API_URL} = process.env进行访问;

答案 5 :(得分:0)

尝试 “ Content-Type”:“ application / x-www-form-urlencoded”, 接受:“ application / json”

答案 6 :(得分:0)

确保将 localhost 更改为 your_ip_address,您可以通过在命令提示符中键入 ipconfig 来找到该值

尝试添加到您的 AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 7 :(得分:-1)

解决方案是: 在Android上,您需要使用file://作为前缀指定文件路径。所以这样做:

      const audio = {
        uri: 'file://' + this.recorder.fsPath,
        type: 'video/mp4',
        name: filename
      }
相关问题