Search code examples
react-nativeaxios

Network error with axios and react native


I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:

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)

This is my axios call in my react native component:

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

Solution

  • It seems that unencrypted network requests are blocked by default in iOS, i.e. https will work, http will not.

    From the docs:

    By default, iOS will block any request that's not encrypted using SSL. If you need to fetch from a cleartext URL (one that begins with http) you will first need to add an App Transport Security exception.