我现在正在尝试通过React学习NODEJS。
在正常情况下,编辑帖子的请求为:
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);
}
});
});
带有放置请求。
但是我在发布请求中看到了另一种语法,如下所示:
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));
});
});
这两个之间有什么区别吗?
答案 0 :(得分:-2)
不在代码本身中。区别只是合乎逻辑的。在REST-Conventions中,进行POST请求以创建新资源,而PUT请求则交换现有资源。
在您的第一个示例中,将更新现有资源ID。在第二个示例中,更新被定义为资源本身。由于更新本身就是一种资源,因此您必须发布新的更新而不是PUT。
如果要使用RESTful,则应使用put。但是,这两个动词在语义上没有区别。