HTML Fetch API

🌐 Introduction to the Fetch API

The Fetch API is a modern JavaScript interface for making network requests to retrieve resources like JSON, text, images, or any other data from servers. It’s a cleaner, more powerful alternative to the older XMLHttpRequest and uses Promises for easier asynchronous code. πŸš€

>>β€œFetching data asynchronously makes the web faster and more interactive.” πŸ”„

πŸ“Œ Basic Fetch Syntax

Use fetch() to make a GET request and handle the response:

Simple Fetch Example

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

βš™οΈ Fetch with Async/Await

Modern JavaScript lets you write cleaner asynchronous code using async and await:

Fetch with Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}
fetchData();

πŸ“€ Sending Data with POST Request

You can also send data to servers using POST or other HTTP methods by passing an options object:

POST Request Example

fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch(error => {
  console.error('Error:', error);
});

🧠 Useful Fetch Options

OptionDescription
methodHTTP method: GET, POST, PUT, DELETE, etc.
headersRequest headers as an object
bodyRequest payload (string or FormData)
modeCORS mode: cors, no-cors, same-origin
credentialsInclude cookies with requests: omit, same-origin, include

πŸ’‘ Handling Different Response Types

Fetch responses can be parsed as:

  • response.json() – Parse JSON data
  • response.text() – Plain text
  • response.blob() – Binary data (images, files)
  • response.formData() – Form data
  • response.arrayBuffer() – Low-level binary data

🧠 Tips & Best Practices

  • Always check response.ok to handle HTTP errors gracefully.
  • Use try/catch or .catch() to handle network errors.
  • Consider CORS restrictions when making cross-origin requests.
  • Use HTTPS endpoints for secure data transfer.

πŸ”— Learn More

>>β€œFetch API simplifies networking β€” build fast, reactive web apps!” ⚑