【问题标题】:AxiosError: Network Error on Android React Native ExpoAxiosError:Android React Native Expo 上的网络错误
【发布时间】:2022-10-31 03:58:23
【问题描述】:

我在尝试获取请求时不断收到 Axios 网络错误。在 iOS 上一切正常。它仅在发生这种情况的android上。在模拟器上,我注意到当我可以将基本 url 更改为包含 10.0.2.2 时,它可以工作,但在实际设备上却不行。这是我目前的设置

基本网址是 http://localhost:8888

 const fetchComponent = (props) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

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

  const fetchData = async () => {
    try {
      console.log("props received:", props.link);
      const configurationObject = {
        method: "get",
        url: props.link,
      };
      const response = await axios(configurationObject);

      console.log("response:", response);
      if (response.status === 200) {
        setData(response.data);
        console.log(response.data);
      }
      setLoading(false);
    } catch (error) {
      console.log(error.response);
      setLoading(false);
    }
  };

  return { data, loading };
};

【问题讨论】:

    标签: android react-native axios expo


    【解决方案1】:
    const fetchComponent = (props) => {
      const [data, setData] = useState([]);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        fetchData();
      }, []);
    
      const fetchData = async () => {
    
          console.log("props received:", props.link);
    axios.get(`${props.link}`)
    .then(data=>setData(data.data)
    .catch(err=>setLoading(false))
      };
    
      return { data, loading };
    };
    

    试试这样

    【讨论】:

    • 我已经尝试了上面的代码,但仍然收到网络错误
    • 你能解决吗?
    【解决方案2】:

    您需要更改基本 url 以指向运行服务器的设备的 IP 地址

    例如,如果您的设备的 IP 地址是 192.0.2.235,那么您的基本 url 应该是 http://192.0.2.235:8888

    【讨论】:

      猜你喜欢
      • 2022-06-18
      • 1970-01-01
      • 2020-11-20
      • 2017-09-21
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多