🟨 JavaScript Intermediate

What is the Fetch API?

Answer

The Fetch API is a modern, Promise-based interface for making HTTP requests in the browser, replacing the older XMLHttpRequest. Basic GET: const response = await fetch("https://api.example.com/users"); const data = await response.json();. Fetch returns a Promise that resolves when the response headers are received — you must call .json(), .text(), or .blob() to read the body. Important: Fetch only rejects on network errors, not HTTP errors (404, 500 are resolved responses). Always check: if (!response.ok) throw new Error(`HTTP error \${response.status}`). POST request: fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }). Handle errors: wrap in try/catch. Cancel requests with AbortController: const controller = new AbortController(); fetch(url, { signal: controller.signal }); controller.abort(). For more features (interceptors, timeouts), use axios.