Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

Fetch API

The Fetch API provides an interface for fetching resources asynchronously across the network.

Try It Yourself

      
📋 Copy Robust Fetch with AbortController Snippet
// Robust Fetch with Timeout & AbortController
async function fetchWithTimeout(url, timeoutMs = 5000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const res = await fetch(url, { signal: controller.signal });
    if (!res.ok) throw new Error(`HTTP Error ${res.status}: ${res.statusText}`);
    return await res.json();
  } finally {
    clearTimeout(timer);
  }
}

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Fetch Does Not Reject on HTTP 404 or 500
fetch() only rejects on actual network connection failures. HTTP errors (like 404 Not Found or 500 Internal Server Error) resolve normally! Always verify if (!response.ok).
Trap #2: Missing AbortController Causing Zombie Requests
Without an AbortController, a stalled or slow HTTP request hangs indefinitely in the browser background, wasting bandwidth and memory.
Trap #3: Reading the Response Body Twice
A Fetch response body is a readable stream that can only be consumed once. Calling res.json() then res.text() throws TypeError: body stream already read.
Trap #4: Forgetting Content-Type on POST Payloads
Sending a JSON string via body: JSON.stringify(data) without setting "Content-Type": "application/json" causes backend servers to fail parsing the payload.
Trap #5: CORS Failures Misinterpreted as Network Down
When CORS preflight fails or headers are missing, browsers report generic TypeError: Failed to fetch to prevent leaking security details.

💬 Frequently Asked Questions

How does AbortController cancel an active fetch request?
AbortController provides an abort() method and a signal property. Passing signal to fetch() allows calling controller.abort() to cancel network transfer immediately.
What does response.ok indicate in the Fetch API?
response.ok is a boolean property that is true if the HTTP response status code is within the 200–299 success range.
How do you send authentication headers with fetch?
Pass them in the headers object: headers: { "Authorization": `Bearer ${token}` }.
What is the difference between fetch() and XMLHttpRequest?
fetch() is modern, Promise-based, supports streaming responses, and integrates with service workers, whereas XMLHttpRequest relies on event callbacks.
How do you handle binary file downloads with fetch?
Call await response.blob() or await response.arrayBuffer() instead of response.json().
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement