Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        });
    }
like image 882
smilebomb Avatar asked Mar 19 '18 19:03

smilebomb


People also ask

What is network error in Axios?

Network Error means Axios couldn't connect to your server at all, so it can't get any error code from the server.

Is Axios compatible with react native?

Axios is a widely used HTTP client for making REST API calls. You can use this in React Native to get data from any REST API.

Is Axios a REST API?

Axios is an HTTP client library based on promises. It makes sending asynchronous HTTP requests to REST endpoints easier and helps you perform CRUD operations. This REST endpoint/API could be an external API like the Google API, GitHub API, and so on – or it could be your own backend Node.


1 Answers

If you are trying to call localhost on android simulator created with AVD, replacing localhost with 10.0.2.2 solved the issue for me.

like image 138
Esteban Vega Avatar answered Oct 31 '22 08:10

Esteban Vega