Fetch API

Async & APIs · free study notes · Updated

📚 JavaScript – Fetch API

Quick, clean, and modern way to make HTTP requests in the browser.


1. Simple Explanation

The Fetch API lets you request resources (JSON, images, XML, etc.) over the network and work with the responses in a promise‑based, modern syntax.
Instead of the old XMLHttpRequest, you:

fetch(url, options).then(response => /* handle */).catch(err => /* handle */);
  • fetch(url) – sends a GET request.
  • fetch(url, options) – allows POST, PUT, DELETE, custom headers, body, etc.
  • Returns a Promise that resolves to a Response object.
  • Use response.json(), response.text(), response.blob(), etc., to read the body.

2. Key Points

# Concept Why It Matters
1 Promise‑based Easy chaining, async/await compatibility
2 Response object Contains status, headers, body methods
3 Body methods json(), text(), blob(), arrayBuffer(), formData()
4 CORS Default fetch is same‑origin unless server sets CORS headers
5 Error handling Network errors reject promise; HTTP errors (404, 500) do not – you must check response.ok
6 AbortController Cancel a request, useful for debouncing or component unmounts
7 Credentials credentials: 'include' for cookies / auth
8 Cache cache: 'no-store', 'reload', 'force-cache'
9 Streaming response.body is a readable stream (advanced)
10 Fetch polyfills whatwg-fetch for older browsers

3. Worked Example

Scenario

Send a POST request to an API that returns a JSON object, handle success + error, and cancel if the user navigates away.

// 1️⃣  Create an AbortController
const controller = new AbortController();
const signal = controller.signal;

// 2️⃣  Define request options
const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    // any auth header if needed
  },
  body: JSON.stringify({ name: 'Ada', age: 30 }),
  credentials: 'include', // send cookies
  signal,                 // attach abort signal
  cache: 'no-store',      // always fetch fresh
};

// 3️⃣  Make the request
fetch('https://api.example.com/users', options)
  .then(response => {
    // 4️⃣  Check HTTP status
    if (!response.ok) {
      // Throw an error that will be caught in .catch
      return response.text().then(text => {
        throw new Error(`HTTP ${response.status}: ${text}`);
      });
    }
    // 5️⃣  Parse JSON body
    return response.json();
  })
  .then(data => {
    console.log('Success:', data);
    // render UI, update state, etc.
  })
  .catch(err => {
    if (err.name === 'AbortError') {
      console.warn('Request aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

// 6️⃣  Cancel the request if needed
// Example: user navigates away
window.addEventListener('beforeunload', () => controller.abort());

What’s happening?

  1. AbortController – lets us cancel the request.
  2. Headers & Body – JSON payload, content type.
  3. Credentials – include session cookies.
  4. Error check – response.ok covers 2xx/3xx; otherwise, throw.
  5. JSON parsing – response.json() returns a promise.
  6. Catch – distinguish abort vs. other errors.

4. Quick Revision Summary

# Concept One‑liner
1 fetch(url, options) – Promise returning Response.
2 Response.ok + status – HTTP status.
3 Body methods: json(), text(), blob(), formData().
4 Errors: network → promise rejection; HTTP → check .ok.
5 AbortController – cancel requests.
6 credentials: 'include' – send cookies.
7 cache options: default, no-store, reload, force-cache.
8 CORS – server must allow cross‑origin requests.
9 Async/await syntax is equivalent: const res = await fetch(...).
10 Polyfill needed for IE11 or older browsers.

Quick Code Cheat‑Sheet

// GET
fetch('/api/data')
  .then(r => r.ok ? r.json() : Promise.reject(r))
  .then(data => console.log(data))
  .catch(err => console.error(err));

// POST with JSON
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada' })
}).then(r => r.json());

// Abort
const ac = new AbortController();
fetch('/api/slow', { signal: ac.signal });
ac.abort(); // cancels

Happy fetching! 🚀

Your note

Page 1

Doubt hai is topic me?

Free AI teacher se poocho — 24/7, step by step.