arnebr
arnebr

Reputation: 565

React Native Post Request via Fetch throws Network Request Failed

I've came across the following error. At the moment I developing an Android App with React Native therefore I'm planning to use fetch for doing a post request for me.

fetch("https://XXreachable-domainXX.de/api/test", {
    method: "post",

    body: JSON.stringify({
      param: 'param',
      param1: 'param',

    })
  })
  .then((response) = > response.json())
  .then((responseData) = > {
    ToastAndroid.show(
      "Response Body -> " + JSON.stringify(responseData.message), ToastAndroid.SHORT
    )
  })
  .catch((error) = > {
    console.warn(error);
  });

The app now throws an error:

TypeError: Network request failed

When I change the code to a GET-Request it's working fine, in the browser with a window.alert() as a return it's cool and also the Chrome extension Postman returns data correctly.

Upvotes: 35

Views: 68700

Answers (11)

sudesh vantimar s
sudesh vantimar s

Reputation: 11

I had same issue using the fetch,this is a type error.so try using Axios. This worked for me.

the code which wasnt working :error:[typeError : network Request failed]

return fetch(addProduceApi, { method: 'PATCH', body: bodyParamData, headers: getAuthHeader() })
.then((response: any) => response.json()) .catch((error: any) => console.log('Error in patchProduce: ', error));

the working code:

return axios.patch(addProduceApi,produceData,{ headers: getAuthHeader()}) 

.then((response: any) => response.json()) .catch((error: any) => console.log('Error in patchProduce: ', error));?

Upvotes: 1

AMAL MOHAN N
AMAL MOHAN N

Reputation: 1632

My issue was fixed when I restarted the emulator

Upvotes: 0

Arash Younesi
Arash Younesi

Reputation: 1750

None of the other answers helped me. The problem was headers:

Old header:

fetch(API_HOST, {
                method: 'POST',
                headers: {
                    Accept: 'application/json'
                },
                body: JSON.stringify(data),

Updated header:

fetch(config.API_HOST, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json'  // I added this line
                },
                body: JSON.stringify(data),

Upvotes: 15

devkrkanhaiya
devkrkanhaiya

Reputation: 97

step1> add android:usesCleartextTraffic="true" line in AndroidManifest.xml like:

// add this line ... step2> Delete all debug folder from your android folder..

Upvotes: 3

bcr
bcr

Reputation: 2073

I had this problem on Android due to an expired certificate. The error message I had was com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at Fri Sep 29 16:33:39 EDT 2017 (compared to Fri Dec 08 14:10:58 EST 2017).

I was able to confirm this using digicert.com.

Unfortunately I did have to dig rather deep into the React Native code and debug the XHR code in the bundle (index.android.bundle) in order to find the error message and the URL in question, because it was in some of my logging code, which I obviously didn't log to the console as well. :)

I was helped by this GitHub issue comment.

Upvotes: 0

iuliu.net
iuliu.net

Reputation: 7145

If you run into this problem on emulator make sure you also test it on the device. It's most probably not happening there.

Just so you know there's nothing to worry about if you can work around it.

Upvotes: 0

Stephen King
Stephen King

Reputation: 71

If you have had this error and you are sure everything works well and you are running an emulator, simply close your emulator and fire it up again.

It should run now.

This usually happens after you have hibernated your system for a while

Upvotes: 6

Tuan Nguyen
Tuan Nguyen

Reputation: 2607

Check two cases bellow

  1. Wrong end-point
  2. Internet connection: both real-device, virtual-device

It has eaten 2 hour with the second reason.

Upvotes: -5

tlagreca
tlagreca

Reputation: 365

I had a major issue doing the same on the android emulator. On iOS approving the domain in the info.plist was necessary. To be clear I was attempting to login to my .NET web hosted API.

The fix was to make sure the post data was parameterised.( I'm pretty sure that's a word)

export const loginUser = ({ userName, password }) => {
const data = `UserName=${userName}&Password=${password}&grant_type=password`
    return (dispatch) => {
        dispatch({ type: LOGIN_USER })

        fetch(URL_LOGIN, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: data
            // body: {

            //     UserName: userName,
            //     Password: password,
            //     grant_type: 'password'

            // }

        })
            .then((response) => { 
                loginUserSuccess(dispatch, response)
            })
            .catch((response) => {
                loginUserFailed(dispatch, response)
            })
    };
};

Upvotes: 0

Antonio
Antonio

Reputation: 434

This React Native's error is rather useless, so you need to get the actual underlying error first. The most straightforward way is to write a small native program that would just perform the same query using HttpsURLConnection.

For me the actual error was java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. which has a well known solution: https://developer.android.com/training/articles/security-ssl.html#MissingCa

This is quite likely your case also, given that the browsers and Postman have no problem with the request. To check it run openssl s_client -connect XXreachable-domainXX.de:443 -showcerts. If there are certificate errors, fix them first, it could spare you time writing the native program.

Edit: actually the easiest way to see all underlying android errors for react native is simply running 'adb logcat' in terminal

Upvotes: 15

mp31415
mp31415

Reputation: 6689

Developing with Windows OS/PHP built-in server/react-native Android on device:

  • check server local IP address (ipconfig), e.g. 172.16.0.10
  • in react-native fetch use this URL and proper port (fetch('http://172.16.0.10:8000/api/foo))
  • run PHP built-in server with this specific IP instead of the localhost: php -S 172.16.0.10:8000 ...
  • turn off Windows firewall for the private networks

That fixed the connection problem between Android phone and the local server for me.

Upvotes: 16

Related Questions