为什么使用 HTTP PUT 和 DELETE 方法而不是 POST? [英] Why use HTTP PUT and DELETE methods instead of POST?

查看:49
本文介绍了为什么使用 HTTP PUT 和 DELETE 方法而不是 POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 new_story GET     /story/new(.:format)  {:action=>"new", :controller=>"stories"}
edit_story GET     /story/edit(.:format) {:action=>"edit", :controller=>"stories"}
     story GET     /story(.:format)      {:action=>"show", :controller=>"stories"}
           PUT     /story(.:format)      {:action=>"update", :controller=>"stories"}
           DELETE  /story(.:format)      {:action=>"destroy", :controller=>"stories"}
           POST    /story(.:format)      {:action=>"create", :controller=>"stories"}

在 web 开发中,我使用过其他技术,我只使用过 GETPOST 方法,但是在 Rails 中使用了 RESTful 路由,默认情况下,PUTDELETE 方法用于 updatedestroy 操作.使用 PUTDELETE 有什么好处或需要?我认为这些方法只是执行 POST 的另一种方式 - 但为什么不坚持使用 POST?

In web development I have done with other technologies, I only ever used GET and POST methods, but with RESTful routes in Rails, by default the PUT and DELETE methods are used for the update and destroy actions. What's the advantage or need for using PUT and DELETE? I assume these methods are just another way of doing POST - but why not just stick with POST?

推荐答案

优点主要是语义化,也可以在一定程度上简化 URL.不同的 HTTP 方法映射到不同的操作:

The advantage is mostly semantic, and can also simplify URLs to an extent. The different HTTP methods map to different actions:

POST   => create a new object
DELETE => delete an object
PUT    => modify an object
GET    => view an object

然后,理论上,您可以使用相同的 URL,但使用不同的方法与之交互;用于访问资源的方法定义了实际的操作类型.

Then, in theory, you can use the same URL, but interact with it using different methods; the method used to access the resource defines the actual type of operation.

但实际上,大多数浏览器仅支持 HTTP GET 和 POST.Rails 在 HTML 表单中使用了一些诡计",就像发送了 PUT 或 DELETE 请求一样,即使 Rails 仍然使用 GET 或 POST 来处理这些方法.(这解释了为什么您可能没有在其他平台上使用 DELETE 或 PUT.)

In practice, though, most browsers only support HTTP GET and POST. Rails uses some "trickery" in HTML forms to act as though a PUT or DELETE request was sent, even though Rails is still using GET or POST for these methods. (This explains why you might not have used DELETE or PUT on other platforms.)

这篇关于为什么使用 HTTP PUT 和 DELETE 方法而不是 POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆