简体   繁体   中英

How do I fix a 404 (Not Found) error in a CRUD application?

I'm trying to add an update function to my MERN CRUD app, and I can't get the Update to work properly. I can't figure out how to build either the function to handle the update or the API to carry the command between the app and the database. Whenever I hit submit, I get a 404 error.

Here is my function to handle the update from the page:

  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("/");
  };

Here is my API:

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

And in case they're needed, here is the controller:

  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));
  }

And here is my route:

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

I've been able to console.log the info for the updatedObj, so I'm pretty sure the info from the form is making it as far as the API. And I'm pretty sure it's something small that I'm overlooking.

Many thanks in advance for you help.

In your router ,you don't define post method,

In submitItemEdits funtion, axios should use "put" instead of "post" method

axios.post will send data to the router.post('/api/bucketList/:id' , ()=>{}) route.

So it won't send to the correct router. To update, you need to send data to the router.put("/api/bucketList/:id", ()=>{}) .

To do this you need to use axios.put() instead of axios.post()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM