【发布时间】:2021-10-27 16:28:12
【问题描述】:
我在构建中学习。我正在使用 Reactjs、Nodejs、Mongodb 构建一个博客管理系统。 我想在数据库中存储一些前端值,以便我授予管理员权限的任何人都可以发布、编辑和删除这些值。这些值是网站名称、子名称、侧边栏简介、标题图像和简介图像。
这是创建值的代码:
//create new frontend paramters into database
router.post("/", async (req, res) =>{
const newFrontendValues = new Frontend(req.body);//we called the frontend model we created and we used req.body
try{
const savedFrontendValues = await newFrontendValues.save()//we tried to save the frontend values created
res.status(200).json(savedFrontendValues)
}catch(err){
res.status(500).json(err)
}
});
我在节点中编写了代码,以便在创建它们后获取如下值:
//get frontend parameters
router.get("/:id", async (req, res) =>{
try{
const frontend = await Frontend.findById(req.params.id)
res.status(200).json(frontend)
}catch(err){
res.status(500).json(err)
}
})
我的服务器 api 代码
app.use("/api/frontend", frontend)
在反应中,我想调用值的 _id 但我迷路了。我真的不知道该怎么做。 它在邮递员中可以正常工作,因为我可以直接实现值_id。 见附图
但在 React 中,我希望它是动态的。
这是我的 React 代码:
useEffect(() => {
const fetchFrontendValue = async () =>{
const res = await axios.get("/frontend")
console.log(res.data)
}
fetchFrontendValue()
}, [])
如何将 _id 添加到此
axios.get("/frontend")
【问题讨论】:
-
当您调用
fetchFrontendValue时,是否有包含您要获取数据的id的路由参数?您如何在前端跟踪哪个 id 是该页面/视图的正确 id? -
需要注意的一点:前端永远不应该知道使用了mongodb。它应该只关心对后端进行 HTTP 调用。这些调用的实现方式与 React 代码无关。后端仅负责访问数据库并在响应中创建 JSON 字符串。这种职责分离有助于我们人类更清楚地思考每个系统。话虽如此,这里的解决方案是确保在来自 nodejs 后端的响应中包含 id。
-
为此,
Frontend.findById()返回什么?findById()是什么?这是你写的函数吗?如果是这样,请edit您的问题包括它和任何其他相关代码。 -
我更新了代码以显示创建前端值的代码。你问的是这个吗?
标签: node.js reactjs mongodb axios