首页 > 解决方案 > 如何在反应钩子中从 mongoDB express 服务器 POST 和 GET?

问题描述

从我的 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 })
})

标签: node.jsreactjsmongodbexpressaxios

解决方案


你可以尝试这样的事情,todos每次创建新的 todo 时,use effect for 都会记录值

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>)


推荐阅读