簡體   English   中英

如何從后端獲取數據到前端?

[英]How do i fetch data from the backend to the frontend?

我在我的服務器端(節點 JS)有這個得到 API:

app.get("/todos", async(req, res)=>{
    try {
        const allTodos = await pool.query("select * from todo;");
        res.json(allTodos.rows);
    } catch (err) {
        console.error(err.message);
    }
    })

當然,當我用 Postman 嘗試它時它可以工作。 在這里,我的客戶端(React JS)中有我的 ListTodo:js,我嘗試在其中獲取數據並將其顯示在表格中:

import React, { Fragment, useState, useEffect } from "react";


const ListTodo = () =>{

const [todos, setTodos] = useState([]);

const getTodos = async() => {
    try {
        const response = await fetch("http://localhost:5000/todos")
        const jsonData = await response.json();
        setTodos(jsonData)
    } catch (err) {
        console.error(err.message);
    }
}

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

console.log(todos);
return (
    <Fragment>
      <table class="table">
<thead>
  <tr>
    <th>Description</th>
    <th>Edit</th>
    <th>Delete</th>
  </tr>
</thead>
<tbody>
  {todos.map(todo => (
    <tr>
        <td>{todo.description}</td>
        <td>Edit</td>
        <td>Delete</td>
    </tr>
  ))}
</tbody>
</table>
    </Fragment>
 );
 }
export default ListTodo;

所以如果我嘗試 console.log(jsonData) 我得到 2 個空的 arrays。

它應該是:

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

代替:

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

你不小心聲明了一個新變量

試試這個,告訴我控制台里有什么

useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
  .then(data => data.json())
  .then(setTodos)
  .catch(console.error);
});

我認為您的代碼很好,但問題出在其他問題上,請在控制台中顯示 output。

另外,嘗試將 'http://localhost...' 替換為 'https://jsonplaceholder.typicode.com/users' 並查看獲取是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM