如何在React应用中获取MongoDB对象的_id并拼接至axios请求
问题背景
我正在通过实操项目学习开发,使用React.js、Node.js、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) } })
服务端路由配置
app.use("/api/frontend", frontend)
当前React请求代码
useEffect(() => { const fetchFrontendValue = async () =>{ const res = await axios.get("/frontend") console.log(res.data) } fetchFrontendValue() }, [])
核心疑问
当前在Postman中可以直接填写_id发起请求,功能运行正常,但不清楚在React中如何动态获取对应配置的_id来发起请求,应该如何将_id拼接至axios.get("/frontend")的请求路径中?
解决方案
方案1:适配后端接口(更适合全局配置场景)
博客的全局前端配置通常只会保留1条生效记录,不需要每次传id查询,先给后端新增查询全量配置的接口,直接返回第一条生效配置即可:
// 新增查询全量配置接口,注意要放在get("/:id")路由前面 router.get("/", async (req, res) =>{ try{ const frontendList = await Frontend.find() // 全局配置仅存一条,直接返回第一条即可 res.status(200).json(frontendList[0] || {}) }catch(err){ res.status(500).json(err) } })
前端仅需要补全接口前缀即可正常请求,无需调整原有逻辑:
const res = await axios.get("/api/frontend")
方案2:指定id查询的实现方式
如果业务逻辑要求必须指定id查询,可通过两种方式拼接路径:
- 模板字符串拼接(最常用)
// 配置id可以从新增接口返回值、状态管理、本地存储中获取 const configId = "你的配置id值" const res = await axios.get(`/api/frontend/${configId}`)
- axios params参数传递
const configId = "你的配置id值" const res = await axios.get(`/api/frontend`, { params: { id: configId } })
注意事项
原有请求路径漏了服务端配置的/api前缀,必须补全才能匹配到后端路由。如果是新增配置后需要立即查询对应记录,直接取新增接口返回的savedFrontendValues中的_id字段即可,无需手动存储。
内容的提问来源于stack exchange,提问作者kinhs
相关产品推荐
相关产品推荐

