204有什么用?

204 No Content:服务器成功处理了请求,但没返回任何内容。

你也许会有疑问:“返回一个没有响应体的HTTP/200响应不行吗?”

如果没有响应体,则在大多数场景下,这两种响应码完全等效,但有一种情况下,HTTP/204响应会让浏览器有不同的表现。这种情况就是当用户在浏览器窗口window或者frame/iframe框架中导航的时候。

204 No Content

If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent’s active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent’s active view.

根据RFC part for the status code 204,204的主要作用在Get请求中,阻止窗口在导航时的跳转。

若返回的是200的空body,点击该链接会导致跳转,若是204则不会发生任何事情:

Get请求返回204的接口并不会发生任何事情

用Post还是用Get?

虽然204体现在Get上多一点,但是实际按照规范来说,204更应该用在于服务器已完成请求,但不需要返回实体主体的情况下,还是根据RFC part for the status code 204

204 No Content

The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.

RFC 不支持使用 POST 作为 GET 的通用替代品,因为每个都有其特定的用途和语义。

GET 的目的是检索资源。因此,虽然允许,但 HTTP 204 并不是最佳选择,因为 GET 响应中需要内容

RFC 还专门调出 HTTP 204 作为对 PUT、POST 和 DELETE 的适当响应,但忽略了对 GET 的响应