MERN应用更新失败:POST请求出现404错误求助
我正在开发首个全栈MERN应用,目前能正常从数据库GET数据,但更新记录时POST请求出现问题。参考MongoDB文档完成配置后,对useParams的使用仍有疑问:id是否需要为字符串?尝试在fetch URL末尾添加${params.id.toString()}时,出现以下错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'toString')
使用当前代码提交时,出现404错误:
POST http://localhost:4000/update/undefined 404 (Not Found)
后端路由代码
// This section will help you update a record by id. plantRoutes.route("/update/:id").put(function (req, response) { let db_connect = dbo.getDb("plant-babies-data"); let myquery = { _id: ObjectId(req.params.id) }; let newvalues = { $set: { waterDate: req.body.waterDate }, }; db_connect .collection("plants") .updateOne(myquery, newvalues, function (err, res) { if (err) throw err; console.log("1 document updated"); response.json(res); }); });
前端组件POST请求代码
import { useParams } from "react-router"; const params = useParams(); // update database async function submitData(id) { const editedDate = { waterDate: updatedPlant }; // This will send a post request to update the data in the database. await fetch(`http://localhost:4000/update/${params.id}`, { method: "POST", body: JSON.stringify(editedDate), headers: { 'Content-Type': 'application/json' }, }); console.log(`item with id ${id} updated`); }
问题解决办法
解决params.id为undefined的问题
先检查组件对应的路由是否正确定义了:id参数,比如路由需配置为<Route path="/update/:id" element={<YourComponent />} />,如果路由中未声明:id,useParams无法获取到id值,就会出现undefined。另外,确保useParams()在函数组件的顶层调用,不能放在嵌套函数或条件判断语句内部。统一请求方法
后端路由使用.put()处理更新请求,但前端fetch用的是method: "POST",这会导致请求不匹配,后端无法处理该POST请求。需要将前端的请求方法改为"PUT",与后端路由对应。关于id的类型疑问
MongoDB默认的_id是ObjectId类型,后端中ObjectId(req.params.id)的写法是正确的——因为URL中的参数本身就是字符串,无需额外调用toString()。之前的toString()报错是因为params.id为undefined,并非id类型的问题。额外优化:增加参数校验
可以在submitData函数中先判断params.id是否存在,避免发送无效请求:async function submitData(id) { if (!params.id) { console.error("未找到植物ID"); return; } const editedDate = { waterDate: updatedPlant }; await fetch(`http://localhost:4000/update/${params.id}`, { method: "PUT", body: JSON.stringify(editedDate), headers: { 'Content-Type': 'application/json' }, }); console.log(`item with id ${id} updated`); }
内容的提问来源于stack exchange,提问作者Allyson Smith

