|
| 1 | +--- |
| 2 | +id: fetch-api-and-ajax |
| 3 | +title: "Fetch API & Asynchronous HTTP" |
| 4 | +sidebar_label: Fetch API & AJAX |
| 5 | +sidebar_position: 3 |
| 6 | +description: "Master asynchronous HTTP requests in JavaScript with the Fetch API, AbortController timeout handling, streaming responses, and proper error handling." |
| 7 | +tags: [javascript, async, fetch, ajax, http, abortcontroller, web-apis] |
| 8 | +keywords: [javascript, async, fetch, ajax, http, abortcontroller, web-apis] |
| 9 | +--- |
| 10 | + |
| 11 | +import JSEditor from "@site/src/components/js-live-code-editor"; |
| 12 | +import CodeBlock from "@theme/CodeBlock"; |
| 13 | +import firstExample from "!!raw-loader!../_scripts/asynchronous-javascript/live-fetch.js"; |
| 14 | + |
| 15 | +Asynchronous JavaScript and XML (**AJAX**) allows web applications to communicate with backend servers asynchronously without reloading the current page. Modern JavaScript applications utilize the native promise-based **Fetch API** for networking. |
| 16 | + |
| 17 | +## Evolution: `XMLHttpRequest` to `fetch()` |
| 18 | + |
| 19 | +Before `fetch()`, asynchronous requests relied on `XMLHttpRequest` (XHR), which required verbose, callback-driven code: |
| 20 | + |
| 21 | +```javascript title="legacy-xhr.js" |
| 22 | +const xhr = new XMLHttpRequest(); |
| 23 | +xhr.open("GET", "https://api.example.com/data"); |
| 24 | +xhr.onload = function () { |
| 25 | + if (xhr.status >= 200 && xhr.status < 300) { |
| 26 | + console.log(JSON.parse(xhr.responseText)); |
| 27 | + } |
| 28 | +}; |
| 29 | +xhr.onerror = function () { |
| 30 | + console.error("Network Error"); |
| 31 | +}; |
| 32 | +xhr.send(); |
| 33 | +``` |
| 34 | + |
| 35 | +The modern **Fetch API** streamlines networking with standard Promises and cleaner configuration objects: |
| 36 | + |
| 37 | +```javascript title="modern-fetch.js" |
| 38 | +// Modern Promise-based Fetch |
| 39 | +fetch("https://api.example.com/data") |
| 40 | + .then((response) => response.json()) |
| 41 | + .then((data) => console.log(data)) |
| 42 | + .catch((error) => console.error("Fetch Error:", error)); |
| 43 | +``` |
| 44 | + |
| 45 | +## Configuring Requests & Headers |
| 46 | + |
| 47 | +The `fetch()` function accepts two arguments: the target `resource` URL and an optional `options` configuration object. |
| 48 | + |
| 49 | +```javascript title="fetch-config.js" |
| 50 | +async function createUser(userData) { |
| 51 | + const response = await fetch("https://api.example.com/users", { |
| 52 | + method: "POST", // HTTP Method: GET, POST, PUT, DELETE, PATCH |
| 53 | + headers: { |
| 54 | + "Content-Type": "application/json", |
| 55 | + "Authorization": "Bearer YOUR_JWT_TOKEN" |
| 56 | + }, |
| 57 | + body: JSON.stringify(userData), // Serialize JavaScript object to JSON |
| 58 | + mode: "cors", // cors, no-cors, or same-origin |
| 59 | + cache: "no-cache" |
| 60 | + }); |
| 61 | + |
| 62 | + return await response.json(); |
| 63 | +} |
| 64 | + |
| 65 | +``` |
| 66 | + |
| 67 | +## The Fetch Error-Handling Gotcha |
| 68 | + |
| 69 | +Unlike HTTP libraries like Axios, `fetch()` **does not reject** its Promise on HTTP error status codes (such as `404 Not Found` or `500 Internal Server Error`). A `fetch()` Promise only rejects on network failures or blocked requests. |
| 70 | + |
| 71 | +To handle HTTP errors properly, check the `response.ok` boolean property (`status` between 200–299): |
| 72 | + |
| 73 | +```javascript title="safe-fetch.js" |
| 74 | +async function safeFetch(url) { |
| 75 | + try { |
| 76 | + const response = await fetch(url); |
| 77 | + |
| 78 | + // Check for HTTP error status codes (4xx, 5xx) |
| 79 | + if (!response.ok) { |
| 80 | + throw new Error(`HTTP Error! Status: ${response.status} ${response.statusText}`); |
| 81 | + } |
| 82 | + |
| 83 | + const data = await response.json(); |
| 84 | + return data; |
| 85 | + } catch (error) { |
| 86 | + console.error("Request Failed:", error.message); |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +``` |
| 91 | + |
| 92 | +## Aborting Requests & Timeouts (`AbortController`) |
| 93 | + |
| 94 | +To cancel ongoing network requests or implement request timeouts, use the native **`AbortController`** interface: |
| 95 | + |
| 96 | +```javascript title="abort-fetch.js" |
| 97 | +async function fetchWithTimeout(resource, options = {}) { |
| 98 | + const { timeout = 5000 } = options; |
| 99 | + |
| 100 | + // 1. Create an AbortController instance |
| 101 | + const controller = new AbortController(); |
| 102 | + const id = setTimeout(() => controller.abort(), timeout); |
| 103 | + |
| 104 | + try { |
| 105 | + const response = await fetch(resource, { |
| 106 | + ...options, |
| 107 | + signal: controller.signal // Connect signal to fetch |
| 108 | + }); |
| 109 | + clearTimeout(id); |
| 110 | + return await response.json(); |
| 111 | + } catch (error) { |
| 112 | + if (error.name === "AbortError") { |
| 113 | + throw new Error("Request timed out!"); |
| 114 | + } |
| 115 | + throw error; |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +``` |
| 120 | + |
| 121 | +## Interactive Playground: Live Fetch Explorer |
| 122 | + |
| 123 | +Run the live `fetch()` request below using JSONPlaceholder API: |
| 124 | + |
| 125 | +<JSEditor title="Live Fetch Playground" run={true}> |
| 126 | + {firstExample} |
| 127 | +</JSEditor> |
| 128 | + |
| 129 | +## Best Practices |
| 130 | + |
| 131 | +1. **Always Check `response.ok`**: Never assume a resolved `fetch()` promise indicates a successful data payload. |
| 132 | +2. **Set Request Timeouts**: Wrap network calls with `AbortController` to prevent hanging pending requests on poor connections. |
| 133 | +3. **Use Typed Response Parsing**: Match body parsing methods to payloads (`.json()`, `.text()`, `.blob()`, or `.arrayBuffer()`). |
| 134 | + |
| 135 | +## Knowledge Check |
| 136 | + |
| 137 | +### Exercise Requirements: |
| 138 | + |
| 139 | +Write a reusable function `postJSON(url, payload)` using `async/await` that sends a `POST` request, handles non-2xx HTTP errors properly, and returns the parsed JSON response. |
| 140 | + |
| 141 | +```javascript title="solution.js" |
| 142 | +async function postJSON(url, payload) { |
| 143 | + const response = await fetch(url, { |
| 144 | + method: "POST", |
| 145 | + headers: { |
| 146 | + "Content-Type": "application/json" |
| 147 | + }, |
| 148 | + body: JSON.stringify(payload) |
| 149 | + }); |
| 150 | + |
| 151 | + if (!response.ok) { |
| 152 | + throw new Error(`Failed to POST to ${url} - Status: ${response.status}`); |
| 153 | + } |
| 154 | + |
| 155 | + return await response.json(); |
| 156 | +} |
| 157 | + |
| 158 | +``` |
| 159 | + |
| 160 | +:::success Phase 04 Complete! |
| 161 | +Congratulations! You have completed **Phase 04: Asynchronous JavaScript**. Proceed to **Phase 05: DOM & Browser APIs** to build interactive Web applications! |
| 162 | +::: |
0 commit comments