Course contentsShow
← Web Development
Lesson 828 of 2,98215. Browser NetworkingFree lesson

The Response Object: Properties and Status Handling

Explore Response object properties like ok, status, statusText, and headers for proper response validation.

The Response Object: Properties and Status Handling

What you'll learn: How to inspect and validate the Response object returned by fetch() to determine if your request succeeded or failed.

When you use fetch() to make a network request, it returns a Promise that resolves to a Response object. This object doesn't just contain the data you requested—it includes crucial information about the response itself. Think of it like receiving a package in the mail: before you open it, you check the shipping label, look for damage, and verify it's actually for you.

Core Response Properties

The Response object provides several essential properties:

  • response.ok — A boolean that's true if the status code is in the 200–299 range (success), false otherwise. This is your quick "did it work?" check.

  • response.status — The numeric HTTP status code (200, 404, 500, etc.). This tells you exactly what happened.

  • response.statusText — A human-readable message corresponding to the status code (e.g., "OK", "Not Found", "Internal Server Error").

  • response.headers — A Headers object containing all response headers, like content type or caching instructions.

Why This Matters

fetch() only rejects for network failures (like being offline). It doesn't reject for HTTP errors like 404 or 500. That means a "failed" request still resolves successfully—you must manually check these properties to handle errors properly.

fetch('https://api.example.com/data')
  .then(response => {
    console.log(response.status);      // e.g., 404
    console.log(response.statusText);  // e.g., "Not Found"
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return response.json();
  })
  .catch(error => console.error('Request failed:', error));

Key Takeaway: Always check response.ok or response.status before processing response data—fetch() won't automatically treat HTTP errors as rejections.