我在建筑中學習。我正在使用 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)
}
});
我在 node 中撰寫了代碼以在創建它們后獲取這樣的值:
//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 中,我希望它是動態的。
這是我的反應代碼:
useEffect(() => {
const fetchFrontendValue = async () =>{
const res = await axios.get("/frontend")
console.log(res.data)
}
fetchFrontendValue()
}, [])
我如何將 _id 添加到這個
axios.get("/frontend")
uj5u.com熱心網友回復:
您想查看獲取請求引數。通常作為慣例,人們在 URL 中傳遞它們。所以它會類似于http://localhost:5000/api/frontend?id=617944dc7e00022337a483be78在 API 端,你會用來req.body.id將它傳遞給資料庫。還有其他方法可以做到這一點,但這是最常見的,因為一些舊瀏覽器會洗掉附加到 GET 請求的引數。這是一個鏈接:https : //www.w3schools.com/tags/ref_httpmethods.asp
uj5u.com熱心網友回復:
您應該考慮尋求完整的解決方案。在基本層面上,您應該遵循以下步驟
實作一個后端路由
/getall,以這種方式提取資料庫中的所有專案await Frontend.find({})在前端呈現獲取的串列,使每個專案都是 React UI 專案,并且作為每個專案的一部分,您有用于洗掉和更新專案資料的按鈕
{backendData?.map((item, index)=><SingleItem key={item?._id} data={item} />)}由于每個 SingleItem 都有更新和洗掉按鈕以及 mongodb ID 作為資料的一部分,因此單擊更新和洗掉按鈕,您將從資料中獲取 id 并在后端呼叫相關的 DB Url
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/339447.html
