React native expo 移动应用程序显示网络错误

问题描述

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 服务器使用 axios 获取数据。但是在获取数据时,它显示网络错误。并且没有数据显示。我正在使用 axios 对 JSON 服务器进行 api 调用。并在 EXPO Go 应用程序中对其进行测试,该应用程序可在 Playstore 中获得。但是从 catch 块中,它抛出异常为“网络错误。请任何人帮助我。”

解决方法

您忘记了 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...