HTTP response status code 204 No Content is returned by the server to indicate that a HTTP request has been successfully completed, and there is no message body.
A 204 No Content response is cacheable by default and an ETag header is included in this case. If the default behavior needs to be overridden then the response must include the appropriate HTTP caching headers.
Usage
When the 204 No Content status code is received, it is in HTTP response to a HTTP operation such as a POST, PUT, or DELETE, where no message body is expected. In some instances, a server will instead return a 200 OK status code with no message body and a Content-Length specifier as 0.
An example of how this can be used is the result of a HTTP request generated by a user that presses a “Save» button on a form. The server commits the changes and relies on the client informing the user of success.
Depending on the operation, there are other more appropriate HTTP status codes that can be used to indicate there is no message body. For example, a conditional GET might return a 304 Not Modified status code to indicate that the resource does not have to be retrieved, and will not be present in the HTTP response.
Example
In the example, the client posts XML data to the server that defines a job to be complete. The server responds by acknowledging that the data was accepted and the job successfully completed. There is nothing significant to return to the client in the HTTP response, so the 204 No Content status code is appropriate.
Request
POST /job HTTP/1.1
Host: www.example.re
Content-Type: application/xml
Content-Length: 67
<?xml version="1.0">
<job>
<id>125</id>
<task>G01</task>
</job>
Response
HTTP/1.1 204 No Content
Code references
.NET
HttpStatusCode.NoContent
Rust
http::StatusCode::NO_CONTENT
Rails
:no_content
Go
http.StatusNoContent
Symfony
Response::HTTP_NO_CONTENT
Python3.5+
http.HTTPStatus.NO_CONTENT
Java
java.net.HttpURLConnection.HTTP_NO_CONTENT
Apache HttpComponents Core
org.apache.hc.core5.http.HttpStatus.SC_NO_CONTENT
Angular
@angular/common/http/HttpStatusCode.NoContent
Takeaway
HTTP response status code 204 No Content indicates that a HTTP request has been completed successfully, and any information being returned is in the HTTP headers. No message body will be present.
See also
- 304 Not Modified
- RFC 7231
Last updated: August 2, 2023
BNAME.RU » Код HTTP запроса 204 No Content
Что означает код 204 No Content?
Запрос обработан успешно, но возвращать данные не требуется. Также новая или обновленная информация может быть возвращена в ответе, но в итоге она не будет отличаться относительно того, что было первоначально отправлено на сервер и, таким образом, считается, что клиент уже имеет актуальную информацию. Если клиент является браузером, то он не должен изменять отображение документа, а его состояние до и после отправки запроса не должно изменяться. Этот статус ответа в основном используется для указания успешности запроса, поскольку данные и ракурс данных не должны изменяться, даже если (или с учетом) новая (обновленная информация) уже отображается в ракурсе документа. 204 — не должно содержать тело ответа. Если он есть, он обычно игнорируется, и одна пустая строка считается присутствующей после заголовков.
Код ответа HTTP 204 No Content
Success status показывает, что запрос выполнен успешно, но клиенту не нужно уходить со своей текущей страницы.
Это может быть использовано, например, при реализации функции «сохранить и продолжить редактирование» для вики-сайта. В этом случае запрос PUT
будет использоваться для сохранения страницы, и будет отправлен ответ 204 No Content
, чтобы указать, что редактор не должен быть заменен какой-либо другой страницей.
По умолчанию ответ 204 кэшируется ( заголовок ETag
включен в такой ответ).
HTTP Status 204 (No Content) indicates that the server has successfully fulfilled the request and that there is no content to send in the response payload body.
The server might want to return updated meta-information in the form of entity headers, which, if present, SHOULD be applied to the current document’s active view if any.
The 204 response MUST NOT include a message-body and thus is always terminated by the first empty line after the header fields.
1. Cacheable
By default, 204 (No Content)
the response is cacheable. If caching needs to be overridden then the response must include cache respective cache headers.
For example, you may want to return status 204 (No Content)
in UPDATE operations where request payload is large enough not to transport back and forth. The user agent will send the payload to the server to update the resource.
If the operation is successful, the server will respond with 204
to indicate the success so that client application can update its UI to inform the user about the operation’s success.
It is also frequently used with interfaces that expect automated data transfers to be prevalent, such as within distributed version control systems.
2. Resolving lost update problem
With status 204, the server may also include an HTTP header ETag
to let the client validate client-side resource representation before making a further update on the server – to avoid the lost update problem.
Lost update problem happens when multiple people edit a resource without knowledge of each other’s changes.
In this scenario, the last person to update a resource “wins,” and previous updates are lost.
ETags can be used in combination with the If-Match header to let the server decide if a resource should be updated. If ETag does not match then the server informs the client via a 412 (Precondition Failed)
response.
Reference: 204 No Content
The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
Metadata in the response header fields refer to the target resource and its selected representation after the requested action was applied.
For example, if a 204 status code is received in response to a PUT request and the response contains an ETag header field, then the PUT was successful and the ETag field-value contains the entity-tag for the new representation of that target resource.
The 204 response allows a server to indicate that the action has been successfully applied to the target resource, while implying that the user agent does not need to traverse away from its current “document view” (if any). The server assumes that the user agent will provide some indication of the success to its user, in accord with its own interface, and apply any new or updated metadata in the response to its active representation.
For example, a 204 status code is commonly used with document editing interfaces corresponding to a “save” action, such that the document being saved remains available to the user for editing. It is also frequently used with interfaces that expect automated data transfers to be prevalent, such as within distributed version control systems.
A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.
A 204 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls1.
- 1 Calculating Heuristic Freshness RFC7234 Section 4.2.2
- Source: RFC7231 Section 6.3.5
204 CODE REFERENCES
Rails HTTP Status Symbol :no_content
Go HTTP Status Constant http.StatusNoContent
Symfony HTTP Status Constant Response::HTTP_NO_CONTENT
Python2 HTTP Status Constant httplib.NO_CONTENT
Python3+ HTTP Status Constant http.client.NO_CONTENT
Python3.5+ HTTP Status Constant http.HTTPStatus.NO_CONTENT
.NET HttpStatusCode.NoContent
Rust http::StatusCode::NO_CONTENT
Java java.net.HttpURLConnection.HTTP_NO_CONTENT
Apache HttpComponents Core org.apache.hc.core5.http.HttpStatus.SC_NO_CONTENT
Angular @angular/common/http/HttpStatusCode.NoContent
204 status code example
Here is an example of a request and response that could result in a 204 status code:
Request
DELETE https://example.com/user/123 HTTP/1.1
Host: example.com
Authorization: Bearer <access_token>
Response
HTTP/1.1 204 No Content
Date: Wed, 16 Mar 2023 12:00:00 GMT
Server: nginx
In this example, the client is sending a DELETE request to delete a user resource with ID 123 on the example.com
server. The request includes an Authorization
header with an access token to authenticate the request.
The server processes the request successfully and sends a 204 No Content status code in response, which indicates that the request has been successfully processed, but there is no response body to send back to the client. The server does not send any content in the response body because there is no content to send, as the resource has been successfully deleted.
The server also includes a few headers like Date
and Server
in the response, which provide additional information about the response. The 204 status code is often used for DELETE requests, where the client wants to delete a resource and does not expect any response content.
What is the difference between a 200 and 204 status code?
The main difference between a 200 and 204 status code is that a 200 status code indicates that the server has successfully processed the request and is returning a response with a message body containing the requested information, whereas a 204 status code indicates that the server has successfully processed the request, but there is no response body to send back to the client.
In other words, a 200 response contains a response body with data, whereas a 204 response does not contain any response body.
Here are some more specific differences between these two status codes:
- A 200 status code is used when the server successfully processes the request and returns a response with a message body containing the requested information. This could include HTML content, JSON data, or any other type of content that the client requested.
- A 204 status code is used when the server successfully processes the request, but there is no content to return to the client. This is typically used for requests where the client wants to indicate that it has finished processing a request, such as a DELETE request.
In general, a 200 status code is used for most types of successful requests, while a 204 status code is used when the server has processed the request successfully, but there is no content to return to the client.
Additional resources
- Learn about web development
- Learn about SEO
- Web development services from WebFX
- SEO services from WebFX
- MDN Web Docs
- W3Schools
Return to List of HTTP Status Codes