Why use HTTP PUT and DELETE methods instead of POST?

后端 未结 4 1862
情书的邮戳
情书的邮戳 2020-11-29 04:42
 new_story GET     /story/new(.:format)  {:action=>\"new\", :controller=>\"stories\"}
edit_story GET     /story/edit(.:format) {:action=>\"edit\", :controll         


        
4条回答
  •  爱一瞬间的悲伤
    2020-11-29 05:12

    Here's the "methods" section of the HTTP 1.1 spec; it defines lots of methods, and they all have different benefits and tradeoffs. POST is the most flexible, but the tradeoffs are numerous: it's not cacheable (so the rest of the internet can't help you scale), it isn't safe or idempotent so the client can't just resend it gets an error, and it is no longer clear exactly what you're trying to accomplish (because it's so flexible). I'm sure there are others but that ought to be sufficient. Given all that, if the HTTP spec defines a method that does exactly what you want your request to do, there's no reason to send a POST instead.

    The reason POST is so common is that, historically at least, web browsers only supported GET and POST. Since GET is defined to be safe and idempotent (even though many applications don't adhere to that), the only safe way to modify data was to send a POST. With the rise of AJAX and non-browser clients, that is no longer true.

    BTW, the mapping @mipadi gave is the standard mapping, but it isn't the only valid one. Amazon S3, for instance, uses PUT to create resources. The only reason to use POST is if the client doesn't have sufficient knowledge to create the resource, e.g., you back your resources with a relational database and use artificial surrogate keys.

提交回复
热议问题