ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

AJAX & Fetch API Tutorial• 6 min read

Modern Fetch API & Promises

fetch(), response.json(), and the response.ok status check trap

The modern fetch() API provides a clean, Promise-based interface that replaces clunky callback-based XMLHttpRequest.

The Critical response.ok Trap

IMPORTANT GOTCHA: fetch() does NOT reject its Promise on HTTP 404 or 500 error responses!

A fetch() promise only rejects on network failures (loss of internet connection, DNS failure, CORS block).

You must ALWAYS check if (!response.ok) (status 200-299) before reading response data.

Idiomatic Fetch with Promise Chaining
fetch("https://api.codexia.org/courses/javascript")
  .then((response) => {
    // Explicitly check HTTP status
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json(); // Parses JSON body asynchronously
  })
  .then((courseData) => {
    console.log("Fetched course:", courseData.title);
  })
  .catch((error) => {
    console.error("Network or HTTP failure:", error.message);
  });
Guards against 404/500 errors by verifying response.ok.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Does a standard `fetch("https://example.com/api")` promise reject if the server returns a 404 Not Found status?