【问题标题】:How to POST and GET from mongoDB express server in react hooks?如何在反应钩子中从 mongoDB express 服务器 POST 和 GET?
【发布时间】:2021-11-24 15:06:09
【问题描述】:

从我的 API 端点获取数据时出现错误。 我可以发送数据并通过postTodo()方法更新/删除它们。

我已将其添加到 useEffect() 中,以便在完成或删除 Todo 时向服务器发送数据。

但是每当我重新加载页面时,在 devtools 中,todos 数组是 []

我们将不胜感激。谢谢。

Todo.jsx

  const postTodo = (todos) => {
    console.log(todos);
    axios.post("http://localhost:4000/api/todos", todos, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.log(err);
      })
  }
  useEffect(() => {
    postTodo(todos) 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [todos])

  useEffect(() => {
    axios.get("http://localhost:4000/api/todos", {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
      .then(res => {
        console.log(res);
        setTodos(res.data.todos)
      })
      .catch(err => {
        console.log(err);
      })
  }, [])

server.js

const authCheck = (req, res, next) => {
  if (req.headers['authorization']) {
    const token = req.headers['authorization'].split(" ")
    if (token[0] !== 'Bearer') {
      return res.send({ status: 'error', error: 'invalid request' });
    } else {
      req.jwt = jwt.verify(token[1], process.env.jwtSECRET);
      return next();
    }
  }
}

app.post("/api/todos", authCheck, async (req, res) => {
  const todos = req.body
  console.log(todos);
  const { id } = req.jwt
  const user = await User.findByIdAndUpdate(id, { "todos": todos })
  // console.log(user);
})
app.get("/api/todos", authCheck, async (req, res) => {
  const { id } = req.jwt
  const user = await User.findById(id)
  log(user) //user.todos is empty
  res.send({
    status: "ok", todos: user.todos })
})

【问题讨论】:

  • postTodo(todos) in useEffect 在第一次调用时总是将 todos 数组更新为空,这样你总是得到一个空数组
  • 那我该怎么办?

标签: node.js reactjs mongodb express axios


【解决方案1】:

你可以试试这样,todos 的使用效果会在你每次创建新的待办事项时记录值

const postTodo = (todos) => {
  console.log(todos);
  axios.post("http://localhost:4000/api/todos", todos, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
    .then(res => {
      console.log(res);
      getTodos()
    })
    .catch(err => {
      console.log(err);
    })
}

const getTodos = () => {
  axios.get("http://localhost:4000/api/todos", {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      }
    })
    .then(res => {
      console.log(res);
      setTodos(res.data.todos)
    })
    .catch(err => {
      console.log(err);
    })
}

const newTodo = () => {
  const allTodos = [...todos];
  allTodos.push("new Todo at:" + new Date())
  postTodo(allTodos)
}

useEffect(() => {
  console.log('todo-list', todos)
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos])

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

return (<button onClick={() =>  }> Add Todo </button>)

【讨论】:

    【解决方案2】:

    问题解决了, 实际上是useEffect() 问题。 我删除了 UseEffect 并在每次 useState 挂钩更新后添加 postTodos 方法。

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 2021-07-18
      • 2020-03-19
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多