React+Mongoose中findOne因字段不匹配返回404错误求助
React+Express/Mongoose架构下通过userId查询FicheUser返回404错误
问题现象
- 前端基于React开发,后端采用Express+Mongoose架构
/路由的findFicheUser查询功能正常运行- 调用
/:id路由的findSingleFicheUser方法时,始终触发catch逻辑并返回404错误
问题根源
前端请求URL中传入的参数是authCtx.userId,对应数据库中FicheUser文档的userId字段;但后端代码错误地使用FicheUser.findOne({_id: req.params.id})去匹配文档的_id字段,两者不匹配导致查询失败:
- 数据库FicheUser文档的
_id:ObjectId('64148c621b64390be9b21ea2') - 数据库FicheUser文档的
userId:"64148befb3095018307b3840"(即前端传入的参数值)
解决方案
修改后端的查询条件,将匹配_id字段改为匹配userId字段即可解决问题。
修改后的后端代码
router.get("/", auth, postCtrl.findFicheUser); // 此路由正常工作 router.get("/:id", auth, postCtrl.findSingleFicheUser); exports.findSingleFicheUser = (req, res, next) => { console.log("req.params.id==>", req.params.id); // 将查询条件从 _id 改为 userId FicheUser.findOne({ userId: req.params.id }) .then((ficheUser) => { if (!ficheUser) { throw new Error("ficheUser not found"); } console.log("ficheUser==>", ficheUser); res.status(200).json({ msg: "ficheUser found", ficheUser }); }) .catch((error) => { res.status(404).json({ msg: "ficheUser not found", error }); }); };
前端代码无需修改
const FicheUser = () => { const authCtx = useContext(AuthContext); const url = `http://localhost:3000/api/ficheUser/${authCtx.userId}`; const fetchHandler = async () => { try { const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Bearer ${authCtx.token}`, }, }); const dataResponse = await response.json(); if (response.ok) { console.log("dataResponse ==>", dataResponse); } else { throw new Error( `获取数据失败 (${response.status}): ${dataResponse.message} ` ); } } catch (error) { console.log("服务器问题:请求未成功"); console.log(error); } }; const isLoggedIn = authCtx.isLoggedIn; if (isLoggedIn) { fetchHandler(); } };
控制台错误信息(翻译后)
服务器问题:请求未成功 FicheUser.js:39 Error: 获取数据失败 (404): undefined at fetchHandler (FicheUser.js:33:1) :7000/ficheUser/6414…4c1
内容的提问来源于stack exchange,提问作者Benamara David
相关产品推荐
相关产品推荐

