0

I am now trying to learn the NODEJS with react.

In the normal scenario request for edit posts will be:

router.put("/:id", function(req, res) {
  Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(
    err,
    updatedCamp
  ) {
    if (err) {
      res.redirect("/campgrounds");
    } else {
      res.redirect("/campgrounds/" + req.params.id);
    }
  });
});

With the put request.

But I saw another kind of syntax with the post request like below:

router.route("/update/:id").post((req, res) => {
  Campground.findById(req.params.id).then(Campground => {
    Campground.username = req.body.username;
    Campground.description = req.body.description;
    Campground.duration = Number(req.body.duration);
    Campground.date = Date.parse(req.body.date);
    Campground.save()
      .then(() => res.json("Campground Updated"))
      .catch(err => res.status(400).json(`Error` + err));
  });
});

Is there any difference between these two?

keikai
  • 14,085
  • 9
  • 49
  • 68

1 Answers1

-2

Not in the code itself. The difference is just a logical one. In REST-Conventions, POST-Requests are made to create new resources and PUT-Requests zu swap an existing resource.

In your first example, the existing resource ID would be updated. In your second example, the update is defined as a resource itself. With the update being a resource itself, you must POST a new update instead of PUT.

If you want to work RESTful, you should use put. But there is no semantical difference between the two verbs.