如何在react钩子中从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 })
})

您可以尝试这样的方法,每次创建新的todo 时,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>)

问题解决了,实际上是useEffect()的问题。我删除了UseEffect并且在每次CCD_ 10钩子更新之后添加了CCD_。

相关内容

  • 没有找到相关文章

最新更新