This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

JavaScript Fetch API Cheatsheet

A quick reference guide for the native JavaScript fetch() API: GET/POST requests, JSON payloads, headers, error handling, credentials, and AbortController.

· Published

The native JavaScript fetch() API provides an asynchronous interface for fetching network resources across modern browsers and Node.js.

Basic Requests

GET Request (JSON)

async function loadUserData() {
  const response = await fetch('https://api.example.com/user/1');
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = await response.json();
  return data;
}

POST Request (JSON Payload)

async function createUser(payload) {
  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify(payload)
  });
  return await response.json();
}

Sending Form Data (multipart/form-data)

const formData = new FormData();
formData.append('username', 'alice');
formData.append('avatar', fileInput.files[0]);

// Omit Content-Type header so the browser sets boundary automatically
await fetch('/upload', {
  method: 'POST',
  body: formData
});

Aborting Requests (AbortController)

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5s timeout

try {
  const res = await fetch('/data', { signal: controller.signal });
  const data = await res.json();
} catch (err) {
  if (err.name === 'AbortError') {
    console.error('Fetch request timed out');
  }
} finally {
  clearTimeout(timeoutId);
}

References

Related topics