Fetch API Cheat Sheet

Here’s a cheat sheet for the Fetch API in JavaScript:

Basic Fetch Request

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

Sending POST Request

const postData = {
  username: 'john_doe',
  password: 'secure_password',
};

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

Handling Headers

const headers = new Headers();
headers.append('Authorization', 'Bearer token123');

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: headers,
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Handling Query Parameters

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');

fetch(`https://api.example.com/data?${params.toString()}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Handling Cookies

fetch('https://api.example.com/data', {
  credentials: 'include',
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Abort Fetch Request

const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 5000);

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

Using Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();

Handling Response Status

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Custom Headers and Content Type

const customHeaders = new Headers({
  'Authorization': 'Bearer token123',
  'Custom-Header': 'value',
});

fetch('https://api.example.com/data', {
  headers: customHeaders,
  method: 'GET',
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

These examples cover various scenarios with the Fetch API. Feel free to customize them based on your specific use cases.