Cannot get data from API for android device (React-Native)

huangapple go评论64阅读模式
英文:

Cannot get data from API for android device (React-Native)

问题

I'm trying to get data from an API to Android, but something happened that prevents me from getting the data or results in a timeout error. I have tested this code on the following platforms:

  1. Snack Expo (Web): It passed and I was able to get the data successfully.

  2. Expo (localhost: web): It passed and I was able to get the data successfully.

  3. Expo (Android Emulator): It failed, as it took a very long time to load and no data was received.

  4. Expo GO (real Device): It failed with the error message "Uncaught Error: java.net.ConnectException: Failed to connect to /ip".

Version:

  • "expo": "~48.0.15",
  • "react": "18.2.0",
  • "react-native": "0.71.8",

This is my code, App.json is following:

App:

import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';

export default function Test2() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = () => {
    console.log("start");
    fetch('https://646ee64209ff19b120864a07.mockapi.io/users')
      .then(response => response.json())
      .then(data => {
        console.log("data:", data);
        setData(data);
      })
      .catch(error => {
        console.error(error);
      })
      .finally(() => {
        console.log("end");
      });
  };

  return (
    <View>
      <FlatList
        data={data}
        renderItem={({ item }) => (
          <View>
            <Text>Id user: {item.id}</Text>
            <Text>Name user: {item.name}</Text>
            <Text>-------------------------</Text>
          </View>
        )}
        keyExtractor={item => item.id}
      />
    </View>
  );
}

App.Json

{
  "expo": {
    "name": "MyApp",
    "slug": "MyApp",
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    "userInterfaceStyle": "light",
    "splash": {
      "image": "./assets/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": true
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/adaptive-icon.png",
        "backgroundColor": "#ffffff"
      }
    },
    "web": {
      "favicon": "./assets/favicon.png"
    }
  }
}

I Tried:

  • Check Internet: good connect

  • Check JSON file: pass

link of JSON I used for test: https://646ee64209ff19b120864a07.mockapi.io/users

英文:

I'm trying to get data from an API to Android, but something happened that prevents me from getting the data or results in a timeout error. I have tested this code on the following platforms:

  1. Snack Expo (Web): It passed and I was able to get the data successfully.

  2. Expo (localhost: web): It passed and I was able to get the data successfully.

  3. Expo (Android Emulator): It failed, as it took a very long time to load and no data was received.

  4. Expo GO (real Device): It failed with the error message "Uncaught Error: java.net.ConnectException: Failed to connect to /ip".

    Version

    • "expo": "~48.0.15",

    • "react": "18.2.0",

    • "react-native": "0.71.8",

  • This is my code, App.json is folowing

    App:

    import React, { useEffect, useState } from &#39;react&#39;;
    import { View, Text, FlatList } from &#39;react-native&#39;;
    
    export default function Test2() {
      const [data, setData] = useState([]);
    
      useEffect(() =&gt; {
        fetchData();
      }, []);
    
      const fetchData = () =&gt; {
        console.log(&quot;start&quot;);
        fetch(&#39;https://646ee64209ff19b120864a07.mockapi.io/users&#39;)
          .then(response =&gt; response.json())
          .then(data =&gt; {
            console.log(&quot;data:&quot;, data);
            setData(data);
          })
          .catch(error =&gt; {
            console.error(error);
          })
          .finally(() =&gt; {
            console.log(&quot;end&quot;);
          });
      };
    
      return (
        &lt;View&gt;
          &lt;FlatList
            data={data}
            renderItem={({ item }) =&gt; (
              &lt;View&gt;
                &lt;Text&gt;Id user: {item.id}&lt;/Text&gt;
                &lt;Text&gt;Name user: {item.name}&lt;/Text&gt;
                &lt;Text&gt;-------------------------&lt;/Text&gt;
              &lt;/View&gt;
            )}
            keyExtractor={item =&gt; item.id}
          /&gt;
        &lt;/View&gt;
      );
    }
    
    

App.Json

{
  &quot;expo&quot;: {
    &quot;name&quot;: &quot;MyApp&quot;,
    &quot;slug&quot;: &quot;MyApp&quot;,
    &quot;version&quot;: &quot;1.0.0&quot;,
    &quot;orientation&quot;: &quot;portrait&quot;,
    &quot;icon&quot;: &quot;./assets/icon.png&quot;,
    &quot;userInterfaceStyle&quot;: &quot;light&quot;,
    &quot;splash&quot;: {
      &quot;image&quot;: &quot;./assets/splash.png&quot;,
      &quot;resizeMode&quot;: &quot;contain&quot;,
      &quot;backgroundColor&quot;: &quot;#ffffff&quot;
    },
    &quot;assetBundlePatterns&quot;: [
      &quot;**/*&quot;
    ],
    &quot;ios&quot;: {
      &quot;supportsTablet&quot;: true
    },
    &quot;android&quot;: {
      &quot;adaptiveIcon&quot;: {
        &quot;foregroundImage&quot;: &quot;./assets/adaptive-icon.png&quot;,
        &quot;backgroundColor&quot;: &quot;#ffffff&quot;
      }
    },
    &quot;web&quot;: {
      &quot;favicon&quot;: &quot;./assets/favicon.png&quot;
    }
  }
}

I Tried:

  • Check Internet: good connect

  • Check JSON file: pass

link of JSON I used for test: https://646ee64209ff19b120864a07.mockapi.io/users

答案1

得分: 1

"After 30 mins, I find the solution.
Because Expo don't have Manifest file, we will do it in another way
Add this code to app.json:

\"android\": {
      \"config\": {
        \"cleartextTraffic\": true
      },}"

//Skip any part if it already exists in your file

英文:

After 30 mins, I find the solution.
Because Expo don't have Manifest file, we will do it in another way
Add this code to app.json:

&quot;android&quot;: {
      &quot;config&quot;: {
        &quot;cleartextTraffic&quot;: true
      },}

//Skip any part if it already exist on your file

答案2

得分: 0

尝试将以下内容添加到您的 androidManifest.xml 文件中:

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

Try adding this in your androidManifest.xml file

&lt;application
    ...
    android:usesCleartextTraffic=&quot;true&quot;&gt;

huangapple
  • 本文由 发表于 2023年5月25日 15:59:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330079.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定