The server actively refused the connection request. This typically means the service is not running, a firewall is blocking the connection, or the server is overloaded and cannot accept new connections.
fetch('http://localhost:8080/api/data')
.then(response => response.json())
.catch(error => console.error('Network error:', error));
The provided authentication token is invalid, expired, or malformed. This prevents the user from accessing protected resources.
// Assuming 'token' is from localStorage or a cookie
fetch('/api/user/profile', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => {
if (!response.ok) throw new Error('Authentication failed');
return response.json();
})
.catch(error => console.error('Auth error:', error));
Input data failed to meet the required validation rules. This could be due to incorrect data types, missing required fields, or values outside acceptable ranges.
const email = 'invalid-email';
if (!/\S+@\S+\.\S+/.test(email)) {
console.error('ERR_VALIDATION_FAILED: Invalid email format.');
}
An unexpected condition occurred on the server. This is a generic error indicating that the server encountered a problem and could not fulfill the request.
// Server-side (e.g., Node.js with Express)
app.get('/data', (req, res) => {
// Simulate an error
throw new Error('Something went wrong on the server!');
res.json({ message: 'Data fetched successfully' });
});
The request took too long to complete and exceeded the allowed time limit. This can be due to slow network conditions or an unresponsive server.
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
fetch('/api/long-operation', { signal: controller.signal })
.then(response => response.json())
.catch(error => {
if (error.name === 'AbortError') {
console.error('ERR_TIMEOUT: The request timed out.');
} else {
console.error('An error occurred:', error);
}
})
.finally(() => clearTimeout(timeoutId));
The request requires authentication credentials that were not provided or were insufficient. The server understands the request but refuses to authorize it.
fetch('/api/admin/settings', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
// 'Authorization': 'Bearer YOUR_TOKEN_HERE' // Token is missing
},
body: JSON.stringify({ theme: 'dark' })
})
.then(response => {
if (response.status === 401) throw new Error('ERR_UNAUTHORIZED: Please log in.');
return response.json();
})
.catch(error => console.error('Access denied:', error));
The server cannot process the request due to something perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', age: 'twenty' }) // 'age' should be a number
})
.catch(error => console.error('Error submitting user data:', error));