skip to Main Content

I’m trying to use fetch to get data from Nest.js from localhost. I get no response. Am I doing something wrong?

const Container = styled.div`
    flex: 1;
    margin: 15px;
    min-width: 300px;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border: 1px solid black;
    max-width: 300px;
  
`
const Name = styled.h1`
    width: 100%;
    height: 135%;
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 20px;
`;
const Member = ({ item }) => {
  return (
    <Container>
        <Name> {item.name}</Name>
        <Birthday> {item.birth_date}</Birthday>
        <Joindate> {item.created_at}</Joindate>
    </Container>
  )
}

export default Member
const Container = styled.div`
    display: flex;
    flex-wrap: wrap;

`
const Members = () => {
    const [data, setData] = useState(null);
    useEffect(() => {
      const getData = async () => {
        try {
          const response = await fetch(
            "http://localhost:3000/api/members"
          );
          let members = await response.json();
          setData(members);
        
        } catch(err) {
     
          setData(null);
        } 
      }
      getData()
    }, [])
  
  return (
   <Container>
      {data && data.map((item) => (
        <Member key={item.id} item={item}  />
        ))}
   </Container>
  )
}

export default Members

What is the issue here?
I’m not getting any response.
these are the data that i want:
id
name
gender
birth_date
created_at
updated_at

What is the issue here?
I’m not getting any response.
these are the data that i want:
id
name
gender
birth_date
created_at
updated_at

2

Answers


  1. Chosen as BEST ANSWER

    This form was causing the issue. Not really sure why but it is fixed now.

     const Urlap = () => {
          const handleSubmit = async (e) => {
            e.preventDefault();
        
            try {
              const response = await fetch("http://localhost:3000/api/members", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  name,
                  birth_date,
                  created_at,
                  gender,
                }),
              });
            } catch (error) {
              console.log(error);
            }
          };
          const [name, setName] = useState(null);
          const [gender, setGender] = useState(null);
          const [birth_date, setBirthdate] = useState(null);
          const [created_at, setJoindate] = useState(null);
          console.log(name, birth_date, created_at);
          return (
            <Container>
              <form action="" id="form" onSubmit={handleSubmit}>
                <input type="text" onChange={(e) => setName(e.target.value)} />
                <input type="date" onChange={(e) => setBirthdate(e.target.value)} />
                <input type="date" onChange={(e) => setJoindate(e.target.value)} />
                <input type="text" onChange={(e) => setGender(e.target.value)} />
                <button type="submit">Tagfelvétel</button>
              </form>
            </Container>
          );
        };
        export default Urlap;
    

  2. Main

    public class Main {
        public static void main(String[] args) {
            if (Arrays.asList(args).contains("--stat")){
                Statisztika.run();
            }
            else{
                HelloApplication.main(args);
            }
        }
    }
    

    Stat

    public class Statisztika {
    
        private static List<Member> members;
        public static void run() {
            try {
                readMembersFromDatabase();
                System.out.printf("Kitiltott tagok száma: %dn", countBannedMembers());         
            } catch (SQLException e) {
                System.out.println("nem sikerült kapcsolódni az adatbázshoz, az alkamazás leáll");
                System.out.println(e.getMessage());
            }
        }
    
       
        private static int countBannedMembers() {
            int count = 0;
            for (Member member: members) {
                if (member.isBanned()) {
                    count++;
                }
            }
             return  count;
        }
    
        private static void readMembersFromDatabase() throws SQLException {
            DBHelper db = new DBHelper();
            members = db.readMembers();
        }
    }
    

    DEP

       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>
    

    DBHELP

    public class DBHelper {
        public static String DB_DRIVER = "mysql";
        public static String DB_HOST = "localhost";
        public static String DB_PORT = "3306";
        public static String DB_NAME = "vizsga";
        public static String DB_USER = "root";
        public static String DB_PASS= "";
    
        private Connection conn;
    
        public DBHelper() throws SQLException {
            String url = String.format("jdbc:%s://%s:%s/%s", DB_DRIVER, DB_HOST, DB_PORT, DB_NAME);
            conn = DriverManager.getConnection(url, DB_USER, DB_PASS);
        }
    
        public List<Member> readMembers() throws SQLException {
            List<Member> members = new ArrayList<>();
            String sql = "SELECT * FROM members";
            Statement statement = conn.createStatement();
            ResultSet result = statement.executeQuery(sql);
            while (result.next()) {
            int id = result.getInt("id");
            String name = result.getString("name");
            String gender = result.getString("gender");
            LocalDate birth_date = result.getDate("birth_date").toLocalDate();
            boolean banned = result.getBoolean("banned");
            Member member = new Member(id, name, gender, birth_date, banned);
            members.add(member);
            }
            return members;
        }
    }
    

    HelloContr

      @FXML
        private TableColumn<Member, String> banned;
    
        private DBHelper db;
        public void initialize(){
           name.setCellValueFactory(new PropertyValueFactory<>("name"));
           gender.setCellValueFactory(new PropertyValueFactory<>("gender"));
            try {
                db=new DBHelper();
                refreshTable();
            } catch (SQLException e) {
              e.printStackTrace();
            }
        }
    
        private void refreshTable() throws SQLException {
            members.getItems().clear();
            members.getItems().addAll(db.readMembers());
        }
    

    OneToMany

     @OneToMany(() => Datas, (data) => data.id)
      @JoinColumn({name: 'data', referencedColumnName: 'data'})
      data: Datas[];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search