Web Foundations

Fetch API

HTTP requests, promises, streaming, abort controllers, and error handling.

Advertisement

Fetch API

HTTP requests, promises, streaming, abort controllers, and error handling.

Overview

Fetch API provides a modern way to make HTTP requests.

Key Concepts

  • Promises — Async request handling
  • Request/Response — HTTP message objects
  • Streaming — Read response as stream
  • Abort Controller — Cancel requests
  • Headers — Work with HTTP headers

Code Examples

<script>
// Basic GET request
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// POST with JSON
fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John', email: 'john@example.com' })
})
.then(response => response.json())
.then(data => console.log('Created:', data));

// Abort controller
const controller = new AbortController();

fetch('https://api.example.com/data', { signal: controller.signal })
  .then(response => response.json())
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request cancelled');
    }
  });

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);

// Streaming response
async function streamResponse() {
  const response = await fetch('https://api.example.com/stream');
  const reader = response.body.getReader();
  
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    console.log('Received chunk:', value);
  }
}

// Error handling
async function fetchData(url) {
  try {
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}
</script>

Practice

Build a data fetching utility with retry logic and abort support.

Advertisement