How to use the Fetch API for HTTP requests

· Category: HTML & CSS

Short answer

The Fetch API provides a modern, promise-based way to make network requests. It replaces XMLHttpRequest with a cleaner interface.

Steps

  1. Call fetch(url) to initiate a request.
  2. Chain .then(res => res.json()) to parse the response.
  3. Handle errors with .catch() or by checking response.ok.

Example

fetch('/api/data')
  .then((res) => {
    if (!res.ok) throw new Error('Network error');
    return res.json();
  })
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

Tips

  • Use async/await for cleaner syntax.
  • Pass an options object for POST requests with headers and body.
  • Abort requests with an AbortController signal.