node.js - 如何在反应钩子中从 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 })
})
解决方案
你可以尝试这样的事情,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>)
推荐阅读
- python - 如何从python中的文本文件中删除特定行
- c# - 是否可以在锁内使用另一个线程来重定向文件中的输出?
- node.js - Npm 找不到文件 - 安装 bcrypt
- context-free-grammar - 查找给定语言的上下文无关语法
- python - 从“azure.storage.blob”导入“BlobServiceClient”时出错
- google-sheets - 为什么 Google 表格中的 0 有时是绿色有时是红色?
- android - 找不到变量 DeviceEventEmitter
- c# - 如何使用 Roslyn 操作 CSHTML
- python - cx-Freeze 无法构建“LookupError:未知编码”
- flurl - Flurl 不遵守超时设置