javascript React Native fetch()不工作android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48079383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:46:54  来源:igfitidea点击:

React Native fetch() not working android

javascriptandroidreact-nativefetch

提问by ppianist

I am trying to call fetch()function.

我正在尝试调用fetch()函数。

It works fine on iOS but not working on Android.

它在 iOS 上运行良好,但不适用于 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 erris {}.

在 iOS 上,它进入,.then()但在 Android 上,它进入.catch()并且err{}

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

它也不适用于模拟器和真实设备。

Any help is appreciated. ^_^

任何帮助表示赞赏。^_^

Error log using Axios

使用 Axios 记录错误

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

当我使用fetch()它时,它.catch()与 {} 一起输入。

I tried with Axiosas below.

我试过Axios如下。

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 }

回答by Mayuresh Patil

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" />

回答by Vishal Dhanotiya

I have solved this issue using the following solution.

我已经使用以下解决方案解决了这个问题。

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

从 Android 9(Pie) 开始,我们需要将networkSecurityConfig设置为 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.xmlinto value/xmlfolder. This Configuration applies to the base configuration, or the default security configuration, of the app and disables all clear text traffic.

现在在value/xml文件夹中创建一个名为network_security_config.xml的新 xml 资源文件。此配置适用于应用程序的基本配置或默认安全配置,并禁用所有明文流量。

<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://codelabs.developers.google.com/codelabs/android-network-security-config/#3

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

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

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

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

回答by sfratini

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

第二个日志指向您的错误。问题是 SSL 证书。解决方法请看这篇文章:

Trust Anchor not found for Android SSL Connection

找不到 Android SSL 连接的信任锚

回答by Renjith Thankachan

You can see in exception traceback that java CertPathValidatorExceptionblocking the network request and check thisanswer related to android

您可以在异常回溯中看到 javaCertPathValidatorException阻塞了网络请求并检查了与 android 相关的这个答案

回答by Perniferous

"I Am Batman"made a good suggestion to use Axios. Axios is a lot simplerand 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的好建议。Axios简单得多,并且可以在 ios/android 上始终如一地工作,而不是使用这些奇怪的错误。这是直接从他们的 github 发出 POST 请求的示例:

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

回答by Nagibaba

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

感谢@mohsenomidi,这个错误是由于http请求而发生的。将此行添加android:usesCleartextTraffic="true"<application/>您的 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

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

回答by Nagibaba

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

如果您看到!近互联网连接图标,也可能是由于 Android 模拟器中的互联网问题。然后您应该将您的网络的 DNS 地址更改为 8.8.8.8。你应该看到这个答案知道如何:https: //stackoverflow.com/a/49332186/6170191

回答by Momenul Islam Rijvi

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

这个工作,android\app\src\main\AndroidManifest.xml

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