How Axios Handles HTTP 204 No Content Responses
The Axios HTTP client handles HTTP 204 No Content responses by resolving the request promise successfully and returning a standard response object containing an empty string as the data payload. Because status 204 falls within the default 2xx success range, Axios does not throw an error, nor does its built-in JSON parser fail when processing the absent body.
Default Status Validation
Axios determines whether to resolve or reject a promise using the
validateStatus configuration option. By default, any HTTP
status code from 200 through 299 is treated as a success:
validateStatus: function (status) {
return status >= 200 && status < 300;
}Since 204 falls within this range, requests completing with this code
trigger the .then() block or return successfully to an
await expression instead of triggering a
.catch() block.
Response Data Parsing
When an HTTP response is received, Axios automatically runs its
default transformResponse functions, which attempt to parse
incoming payloads using JSON.parse.
For an HTTP 204 response:
- The server sends headers followed by an empty body.
- Axios detects that the response body is empty.
- The
JSON.parsestep is bypassed for empty strings, preventingSyntaxError: Unexpected end of JSON inputerrors. - The resulting
response.dataproperty is set to an empty string ("").
Structure of a 204 Response Object
When handling a 204 response, the resolved Axios response object contains the following key properties:
status:204statusText:"No Content"data:""(empty string)headers: An object containing any response headers sent by the server.config: The Axios configuration object used for the request.request: The underlyingXMLHttpRequest(in browsers) orhttp.ClientRequest(in Node.js).
Best Practices for Handling 204 in Application Code
Because response.data is an empty string rather than
null or undefined, applications should avoid
attempting to destructure or access properties on
response.data directly after DELETE,
PUT, or PATCH requests that return 204.
try {
const response = await axios.delete('/api/resource/123');
if (response.status === 204) {
// Action succeeded with no payload returned
console.log('Resource successfully deleted.');
}
} catch (error) {
console.error('Request failed:', error);
}If your application architecture requires empty responses to yield
null instead of an empty string, you can normalize the
response using an Axios response interceptor:
axios.interceptors.response.use((response) => {
if (response.status === 204 && response.data === "") {
response.data = null;
}
return response;
});