0

I've got error "Network request failed" when using fetch in React Native on Android emulator/real device. The code is below:

 fetch('http://localhost:3000/response', {
      method: 'POST',
      headers: {
          Accept: "aplication/json;charset=UTF-8",
          "Content-Type": "application/json"
      },
      body:JSON.stringify({name: "abc", email: "[email protected]"}),
      })
      .then((response) => response.json())
      .then((responseJson) => {

          alert('response object:' + JSON.stringify(responseJson));

          if(responseJson.valid === true){
              // do something

          }

      })
      .catch((error) => {
        console.error(error);
        alert(error);
      });

    });

I've tried to fix it by adding "app.use(cors());" on express server. This fix works when I simulate on web but still fails on emulator or real device.

2
  • did you try to make ///android:usesCleartextTraffic="true"// in android manfiest Commented Mar 31, 2020 at 8:48
  • I use Expo to deploy the app Commented Mar 31, 2020 at 9:59

3 Answers 3

3

You got 2 options:

  • Either implement https for your api endpoint as Neelam mentioned
  • Or add clearTextTraffic true in your AndroidManifest as Abd mentioned here is how you can do that:
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. The first option does not work, I'm using Expo for app deployment so there is not AndroidManifest file but an app.json configuration file instead
2

React native is not worked when you fetch localhost url means instead of localhost you supposed to put an IP address their to make sure that devices are within a network. Just Replace localhost with your IP address. And make sure to connect your mobile with same wifi or network.

fetch('http://yourIPaddress:3000/response', {
      method: 'POST',

Ask if any query.

2 Comments

Thank. Yes, I connected my phone to the machine via USB, changing localhost to my machine IP address but nothing worked!
Check your api call from POSTMAN.
0

use secure server links https, it should work for you

1 Comment

I've found a solution. Just need to replace 'localhost' by '10.0.2.2'' for Android emulator then it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.