18

I am trying to call fetch() function.

It works fine on iOS but not working on Android.

fetch('https://admin.leanpoint.com/Api/User/Login?user=srinu@mainpoint.dk', { 
  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/Login?user=srinu@mainpoint.dk', 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/Login?user=srinu@mainpoint.dk',
     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/Login?user=srinu@mainpoint.dk',
     _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 }
VLAZ
  • 26,331
  • 9
  • 49
  • 67
m00n
  • 1,977
  • 2
  • 13
  • 25

9 Answers9

5

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" />
Mayuresh Patil
  • 2,072
  • 1
  • 21
  • 44
4

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

<application
      ......
      android:usesCleartextTraffic="true"
      ......>
  • 3
    OP's url is already using HTTPS, why would this solution for HTTP solve OP's problem at all? – Danny Sep 08 '21 at 13:44
2

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

Vishal Dhanotiya
  • 2,512
  • 1
  • 13
  • 32
1

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

sebastianf182
  • 9,844
  • 3
  • 34
  • 66
0

"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);
  });
Perniferous
  • 513
  • 6
  • 19
0

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

Renjith Thankachan
  • 4,178
  • 1
  • 30
  • 47
0

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

Nagibaba
  • 4,218
  • 1
  • 35
  • 43
0

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

Nagibaba
  • 4,218
  • 1
  • 35
  • 43
0

I got here for the same error message. What fixed my problem was that I was missing the Content-type on my PUT request. The API I was using didn't show one in the example, but it didn't work at all on Android (and only Android) without it. I needed:

  headers: {
    'Accept': 'application/json',
    'Content-type': 'application/json',
    ...
  },

Hope that helps someone else who gets the same issue!

Cat Sars
  • 23
  • 4