Fetch

A modern browser API for making HTTP requests, providing a more powerful and flexible alternative to XMLHttpRequest.

Overview

The Fetch API provides a JavaScript interface for accessing and manipulating HTTP requests and responses. It uses Promises, making it easier to work with asynchronous operations. Fetch has become the standard way to make HTTP requests in modern web applications, replacing the older XMLHttpRequest API.

Example

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

// Using async/await (modern approach)
async function getUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const user = await response.json();
    return user;
  } catch (error) {
    console.error('Error fetching user:', error);
  }
}

// POST request with JSON data
async function createUser(userData) {
  const response = await fetch('/api/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(userData)
  });

  return response.json();
}

Key Points

  • Returns a Promise
  • More flexible than XMLHttpRequest
  • Supports Request and Response objects
  • Does not reject on HTTP errors (check response.ok)
  • Not supported in IE (polyfill available)

Learn More