Junior
What are HTTP response codes and how do they differ from each other?
sobes.tech AI
Answer from AI
HTTP response codes are three-digit numbers returned by the server in response to a client's request. They indicate the status of request processing and provide information about whether it was successful, if an error occurred, or if additional action is required.
Codes are divided into five classes:
- 1xx (Informational): The request has been received, and the process is continuing.
- 2xx (Successful): The request was successfully received, understood, and processed.
- 3xx (Redirection): Further action is needed by the client to complete the request.
- 4xx (Client Error): The request contains a syntax error or cannot be fulfilled.
- 5xx (Server Error): The server failed to fulfill an apparently valid request.
The differences between the codes lie in their semantics, related to different stages of request processing and possible outcomes.
Examples of commonly used codes:
| Code | Description | Class |
|---|---|---|
| 200 | OK | Successful |
| 201 | Created | Successful |
| 301 | Moved Permanently | Redirection |
| 302 | Found | Redirection |
| 400 | Bad Request | Client Error |
| 401 | Unauthorized | Client Error |
| 403 | Forbidden | Client Error |
| 404 | Not Found | Client Error |
| 500 | Internal Server Error | Server Error |
| 503 | Service Unavailable | Server Error |
// Example of handling an HTTP response in JavaScript
fetch('/api/data')
.then(response => {
if (response.ok) { // Check for successful status (2xx)
return response.json();
} else {
// Handle errors based on status code
console.error(`HTTP Error: ${response.status}`);
if (response.status === 404) {
console.error('Resource not found.');
}
throw new Error(`HTTP Error: ${response.status}`);
}
})
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error loading data:', error);
});