AxiosError:Android React Native Expo上的网络错误

avwztpqn  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(230)

我在尝试获取请求时不断收到Axios网络错误。在iOS上一切都运行得很好。只有在Android上才会发生这种情况。在模拟器上,我注意到当我可以更改基本URL以包含10.0.2.2时,它可以工作,但在实际设备上不行。以下是我当前的设置
基本URL为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 };
};
neekobn8

neekobn81#

您需要更改基本url以指向运行服务器的设备的IP地址
例如,如果设备的IP地址为192.0.2.235,则基本url应为http://192.0.2.235:8888

wmtdaxz3

wmtdaxz32#

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 };
};

像这样尝试

相关问题