【问题标题】:React native expo mobile app is showing network errorReact Native Expo 移动应用程序显示网络错误
【发布时间】:2021-09-12 19:34:29
【问题描述】:
import React, { useEffect, useState } from "react";
import { StyleSheet, View, Button, ScrollView } from "react-native";
import { Spinner, List, ListItem, Text } from "native-base";
import axios from "axios";
const Todo = ({ navigation }) => {
  const [tasks, setTasks] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const loadTasks = async () => {
    try {
      const tasks = await axios.get("http://localhost/tasks");
      setIsLoading(true);
    } catch (e) {
      alert(e);
    }
  };
  useEffect(() => {
    loadTasks();
  }, []);
  if (isLoading) {
    return (
      <View >
        <View>
          <ScrollView>
            <List>
              <ListItem>
                <Text>Simon Mignolet</Text>
              </ListItem>
       </List>
          </ScrollView>
        </View>
        <View style={styles.btn}>
          <Button
            bordered
            primary
            title="Goto homescreen"
            onPress={() => navigation.navigate("Home")}
          />
          <Button title="Add task" />
        </View>
      </View>
    );
  } else {
    return <Spinner />;
  }
};

在上面的代码中,我使用 json server 通过 axios 来获取数据。但是在获取数据时,它显示网络错误。并且没有数据显示。我正在使用 axios 对 JSON 服务器进行 api 调用。并在 Playstore 中提供的 EXPO Go 应用程序中对其进行测试。但是从 catch 块中,它抛出异常为“网络错误。请任何人帮助我。”

【问题讨论】:

  • 使用本地网络 IP 代替 localhost。
  • 我用过两者,甚至 IP 地址和本地主机...但它显示相同的错误 @karikey Vaish

标签: react-native expo json-server


【解决方案1】:

你忘了port

改变

const tasks = await axios.get("http://localhost/tasks");

const tasks = await axios.get("http://localhost:3000/tasks"); 
// 3000 or whatever port you are using for backend

要在您的移动设备上成功运行它,您必须将 localhost 替换为 IPv4 of your local network

【讨论】:

  • 我也是这么做的,兄弟……结果还是一样
  • 确保您的后端在您发送此请求的端口上运行。另外,在chrome上输入smae url,看看会得到什么结果
猜你喜欢
  • 2022-06-18
  • 2022-10-31
  • 2017-09-21
  • 1970-01-01
  • 2020-11-20
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多