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

查看:434
本文介绍了为什么使用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"}

在网络工作中,我完成了其他技术,我只使用过GET和POST方法。但是在Rails中使用RESTful路由时,默认情况下,PUT和DELETE方法用于更新和销毁操作。使用PUT和DELETE的优点或需求是什么?我假设这些方法只是做POST的另一种方式 - 但为什么不坚持使用POST?

In web work 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天全站免登陆