Response Status and StatusText
What you'll learn: How to check if a fetch request succeeded by inspecting response.ok, response.status, and response.statusText.
Understanding HTTP Status Codes
When you make a fetch request, the server sends back more than just data—it also tells you whether the request worked. Think of it like ordering food: the restaurant doesn't just hand you a bag; they might say "Here's your order!" (success) or "Sorry, we're out of that item" (failure).
Every HTTP response includes a status code—a three-digit number that tells you what happened:
200-299: Success300-399: Redirection400-499: Client errors (you made a mistake)500-599: Server errors (server had a problem)
The Three Properties You Need
fetch('https://api.example.com/data')
.then(response => {
console.log(response.ok); // true if status 200-299
console.log(response.status); // Numeric code (e.g., 200, 404)
console.log(response.statusText); // Human-readable text (e.g., "OK", "Not Found")
});
response.ok is the quickest check—it's true only when the status is in the 200-299 range (successful responses).
response.status gives you the exact number, like 200 (OK), 404 (Not Found), or 500 (Server Error).
response.statusText provides a short description like "OK" or "Internal Server Error".
Practical Usage
fetch('/api/user')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status} ${response.statusText}`);
}
return response.json();
})
.catch(error => console.error('Request failed:', error));
Key Takeaway: Always check response.ok to verify success, and use response.status and response.statusText to understand what went wrong when requests fail.