Skip to content
Advertisement

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement