HTTP status codes are a standardized way for web servers to communicate with web browsers and other clients about the outcome of a request.
When a client makes a request to a server, the server responds with an HTTP status code to indicate the success or failure of the request.
HTTP status codes are three-digit numbers that are grouped into different ranges based on their meaning:
- 1xx: Informational – Request received, continuing process
- 2xx: Success – The request was successfully received, understood, and accepted
- 3xx: Redirection – Further action needs to be taken to complete the request
- 4xx: Client Error – The request contains bad syntax or cannot be fulfilled
- 5xx: Server Error – The server failed to fulfill a valid request
Each status code has a specific meaning and can provide additional information about the response. For example:
- 200 OK: The request was successful
- 404 Not Found: The requested resource could not be found
- 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request
These status codes are sent as part of the HTTP response header from the server to the client.
Clients, such as web browsers or JavaScript code, can examine the status code to understand the outcome of their request and take appropriate action.
Performing a Fetch with JavaScript and HTTP Status Codes
Here’s an example of how you can perform a Fetch and handle different HTTP status codes:
fetch('https://api.example.com/data')
.then(response => {
if (response.ok) {
// Handle successful response
return response.json();
} else if (response.status === 404) {
// Handle 404 Not Found error
throw new Error('Resource not found');
} else {
// Handle other errors
throw new Error('Request failed');
}
})
.then(data => {
// Process the response data
console.log(data);
})
.catch(error => {
// Handle any errors that occurred during the request
console.error(error);
});
In this example, the Fetch request is made to the URL https://api.example.com/data
. The response is then checked for different status codes using the ok
property of the response object and the status
property.
If the response has a status code in the 2xx range (indicating success), the JSON data is extracted using the json()
method and processed.
If the response has a 404 status code, an error is thrown. For any other status codes, a generic error is thrown.
The catch
method is used to handle any errors that occurred during the request, such as network errors or server errors.
By handling different HTTP status codes in your Fetch request, you can take specific actions based on the result of the request.
Thanks it was usefull