我应该使用 POST 还是 PUT 作为登录请求,为什么?

Should I use POST or PUT for login request, and why?

我大体上知道它们之间的区别,但对于登录表单,我不确定为什么推荐使用 POST 方法。

广泛地说:因为 PUT 在 HTTP 中具有更具体的语义,并且这些语义与典型的登录表单情况不太匹配。

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- Fielding 2009

POST /foo HTTP/1.1
Content-Type: text/plain

username=foo&password=this_is_a_secret

这个请求几乎可以意味着任何东西;它可能是也可能不是幂等的,它可能是也可能不是“有效只读”。这是非常不置可否的。来自 RFC 7321:

The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics.

相比之下,PUT 意味着更具体的东西

A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response.

因此

PUT /foo HTTP/1.1
Content-Type: text/plain

username=foo&password=this_is_a_secret

建议以后有人这样做时

GET /foo HTTP/1.1

您期待这样的回复

HTTP/1.1 200 OK
Content-Type: text/plain

username=foo&password=this_is_a_secret

换句话说,PUT 的语义与“保存”或“更新插入”的语义非常接近。 “使您的此资源副本看起来像此请求的有效负载。”

请记住,通用 HTTP 组件不一定知道这些消息是关于“登录”的;他们只看到具有 transfer of documents over a network 域语义的消息。这意味着当他们看到您的“登录”PUT 请求时,他们将假设语义与对网络上任何其他资源的 PUT 完全相同,并采取相应的行动。