You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN应用更新失败:POST请求出现404错误求助

全栈MERN应用更新数据时的POST请求问题

我正在开发首个全栈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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:45:38