[英]React Native fetch() not working android
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/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 {}
.在 iOS 上,它输入 .then(
.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 Axios
as below.我尝试使用
Axios
如下。
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 }
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" />
this working, android\app\src\main\AndroidManifest.xml这个工作,android\app\src\main\AndroidManifest.xml
<application
......
android:usesCleartextTraffic="true"
......>
I have solved this issue using the following solution.我已经使用以下解决方案解决了这个问题。
From Android 9(Pie) we need to set networkSecurityConfig into 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.xml into value/xml folder.现在在value/xml文件夹中创建一个名为network_security_config.xml的新 xml 资源文件。 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://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
The second log points to your error.第二个日志指向您的错误。 The problem is the SSL Certificate.
问题是 SSL 证书。 See this post for the solution:
有关解决方案,请参阅此帖子:
Trust Anchor not found for Android SSL Connection 未找到 Android SSL 连接的信任锚
"I Am Batman" made a good suggestion to use Axios . 《我是蝙蝠侠》提出了使用Axios的好建议。 Axios is a lot simpler and is found to work consistently on both ios/android instead of giving use these bizarre errors.
Axios 要简单得多,并且可以在 ios/android 上始终如一地工作,而不是使用这些奇怪的错误。 Here is the example of making a POST request directly off of their github:
这是直接从他们的 github 发出 POST 请求的示例:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
您可以在异常回溯中看到 java CertPathValidatorException
阻止网络请求并检查与 android 相关的这个答案
thanks to @mohsenomidi, this errors happens due to http request.感谢@mohsenomidi,这个错误是由于http请求而发生的。 Add this line to
android:usesCleartextTraffic="true"
to <application/>
in your AndroidManifest.xml将此行添加到 AndroidManifest.xml 中的
android:usesCleartextTraffic="true"
到<application/>
<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
It may be also due to internet issue in Android emulator, if you see !
如果您看到,这也可能是由于 Android 模拟器中的互联网问题
!
near internet connection icon.靠近互联网连接图标。 Then you should Change the DNS address of your network to 8.8.8.8.
然后您应该将您的网络的 DNS 地址更改为 8.8.8.8。 You should see this answer to know how: https://stackoverflow.com/a/49332186/6170191
你应该看到这个答案知道如何: https ://stackoverflow.com/a/49332186/6170191
I got here for the same error message.我来到这里是为了同样的错误信息。 What fixed my problem was that I was missing the Content-type on my PUT request.
解决我的问题是我的 PUT 请求中缺少 Content-type。 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.
我使用的 API 在示例中没有显示,但如果没有它,它在 Android(并且只有 Android)上根本不起作用。 I needed:
我需要:
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
...
},
Hope that helps someone else who gets the same issue!希望能帮助遇到同样问题的其他人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.