如何修复CRUD应用程序中的404(未找到)错误?

时间:2019-04-04 03:01:29

标签: javascript reactjs mongodb axios

我正在尝试将更新功能添加到我的MERN CRUD应用程序,但无法使更新正常工作。我无法弄清楚如何构建用于处理更新的函数或如何在应用程序与数据库之间传递用于承载命令的API。每当我点击“提交”时,都会出现404错误。

这是我处理页面更新的功能:

  onSubmit = e => {
    e.preventDefault();
    const updatedObj = {
      bucketListItem_name: this.state.bucketListItem_name,
      bucketListItem_comment: this.state.bucketListItem_comment,
      bucketListItem_completed: this.state.bucketListItem_completed
    };

    API.submitItemEdits(this.props.match.params.id, updatedObj)
      .then(res => console.log(res.data))
      .catch(err => console.log(err));

      this.props.history.push("/");
  };

这是我的API:

  submitItemEdits: function(id, updatedObj) {
    return axios.post("/api/bucketList/" + id, updatedObj);
  }

如果需要它们,这里是控制器:

  update: function(req, res) {
    db.bucketListItem
      .findOneAndUpdate({ _id: req.params.id }, req.body, {upsert: true})
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  }

这是我的路线:

router
  .route("/:id")
  .get(listController.findById)
  .put(listController.update)
  .delete(listController.remove);

我已经能够console.log记录updatedObj的信息,因此,我很确定表单中的信息可以使它到达API。而且我很确定这是我忽略的小东西。

在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

在路由器中,您没有定义post方法,

在submitItemEdits功能中,axios应该使用“ put”方法而不是“ post”方法

答案 1 :(得分:1)

axios.post会将数据发送到router.post('/api/bucketList/:id' , ()=>{})路由。

因此它不会发送到正确的路由器。要更新,您需要将数据发送到router.put("/api/bucketList/:id", ()=>{})

为此,您需要使用axios.put()而不是axios.post()

相关问题