Home » Android » javascript – React Native fetch() not working android

javascript – React Native fetch() not working android

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to call fetch() function.

It works fine on iOS but not working on Android.

fetch('https://admin.leanpoint.com/Api/User/[email protected]', { 
  method: 'POST', 
  headers: {
    'Authorization': 'Basic c3JpbnVAbWFpbnBvaW50LmRrOnNhaWJhYmE='
  },
})
.then((res) => {
  res.json().then((json) => {
    alert(JSON.stringify(json))
  })
})
.catch((err) => {
  alert(JSON.stringify(err))
})

On iOS, it enters .then() but on Android it enters .catch() and err is {}.

It is not working on Emulator and real device as well.

Any help is appreciated. ^_^

Error log using Axios

When I used fetch() it enters .catch() with {}.

I tried with Axios as below.

axios.post('https://admin.leanpoint.com/Api/User/[email protected]', null, {
      headers: {
        'Authorization': 'Basic c3JpbnVAbWFpbnBvaW50LmRrOnNhaWJhYmE='
      },
      timeout: 2000
    })
    .then((res) => {
      console.log(res.data)
    })
    .catch((err) => {
      console.log(err)
    })

And it returns error like below.

{ [Error: Network Error]
  config:
   { adapter: [Function: xhrAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 2000,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Basic c3JpbnVAbWFpbnBvaW50LmRrOnNhaWJhYmE=' },
     method: 'post',
     url: 'https://admin.leanpoint.com/Api/User/[email protected]',
     data: null },
  request:
   { UNSENT: 0,
     OPENED: 1,
     HEADERS_RECEIVED: 2,
     LOADING: 3,
     DONE: 4,
     readyState: 4,
     status: 0,
     timeout: 2000,
     withCredentials: true,
     upload: {},
     _aborted: false,
     _hasError: true,
     _method: 'POST',
     _response: 'java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.',
     _url: 'https://admin.leanpoint.com/Api/User/[email protected]',
     _timedOut: false,
     _trackingName: 'unknown',
     _incrementalEvents: false,
     responseHeaders: undefined,
     _requestId: null,
     _cachedResponse: undefined,
     _headers:
      { accept: 'application/json, text/plain, */*',
        'content-type': 'application/x-www-form-urlencoded',
        authorization: 'Basic c3JpbnVAbWFpbnBvaW50LmRrOnNhaWJhYmE=' },
     _responseType: '',
     _sent: true,
     _lowerCaseResponseHeaders: {},
     _subscriptions: [] },
  response: undefined }
How to&Answers:

this works for me

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">



<application android:usesCleartextTraffic="true" tools:targetApi="28" />

Answer:

The second log points to your error. The problem is the SSL Certificate. See this post for the solution:

Trust Anchor not found for Android SSL Connection

Answer:

I have solved this issue using the following solution.

From Android 9(Pie) we need to set networkSecurityConfig into AndroidManifast.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config">

    </application>
</manifest>

Now Create a new xml resource file with the name network_security_config.xml into value/xml folder. This Configuration applies to the base configuration, or the default security configuration, of the app and disables all clear text traffic.

<network-security-config>
  <domain-config cleartextTrafficPermitted="false">
    <domain includeSubdomains="true">172.16.33.1</domain>
  </domain-config>
</network-security-config>

For more information, you check the following links

https://codelabs.developers.google.com/codelabs/android-network-security-config/#3

https://developer.android.com/training/articles/security-config

https://medium.com/@son.rommer/fix-cleartext-traffic-error-in-android-9-pie-2f4e9e2235e6

Answer:

“I Am Batman” made a good suggestion to use Axios. Axios is a lot simpler and is found to work consistently on both ios/android instead of giving use these bizarre errors. Here is the example of making a POST request directly off of their github:

    axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Answer:

You can see in exception traceback that java CertPathValidatorException blocking the network request and check this answer related to android

Answer:

thanks to @mohsenomidi, this errors happens due to http request. Add this line to android:usesCleartextTraffic="true" to <application/> in your AndroidManifest.xml

<manifest xmlns:tools="http://schemas.android.com/tools"> .... 
    <application 
        android:usesCleartextTraffic="true" > ... 
    </application> 
</manifest>

https://github.com/facebook/react-native/issues/24627#issuecomment-492159371

Answer:

It may be also due to internet issue in Android emulator, if you see ! near internet connection icon. Then you should Change the DNS address of your network to 8.8.8.8. You should see this answer to know how: https://stackoverflow.com/a/49332186/6170191

Answer:

this working,
android\app\src\main\AndroidManifest.xml

<application
      ......
      android:usesCleartextTraffic="true"
      ......>