Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network Error when use axios in React Native

This is long-standing problem for me and I can't find solution at all.

Within my react native project(react-native-cli), I send request to server using axios package. But when I'm testing with my android phone, it gives [Error: Network Error]. With emulator, it's okay.

I'm sure this is not back-end problem because I've tested with several servers. And I also used fetch instead but got same error.

Here is version information.

"axios": "^0.19.0",
"react": "16.9.0",
"react-native": "0.61.5",

Sometimes, it's working on android phone too. This problem is biggest mystery and I suffered for a long time.

Somebody who experienced this issue, please alive me. Thank you for careful reading.

Sometimes, it's not working even with android emulator. But after deleted original emulator and created new emulator, it's working.

const serverUrl = "https://server.com";
axios.post(serverUrl + "/api/candidates/login", {
            "email": this.state.email ,
            "password": this.state.password
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        }).then((response) => {
                console.log(response.data);
        }).catch((error) => {
                console.log(error);
        })
like image 372
Andrew Terex Avatar asked Jan 05 '20 12:01

Andrew Terex


1 Answers

For Android, instead of using: localhost, use 10.0.2.2.

like image 104
CodeFinity Avatar answered Sep 16 '22 15:09

CodeFinity