🌐 Web Development

Fetch API

Fetch API

The Fetch API is a browser-built-in HTTP client that supports modern Promise-based network requests. It replaces XMLHttpRequest, and combined with async/await it lets you write clean asynchronous code.

πŸ“– Detailed Explanation

The Fetch API is a network request interface introduced in modern browsers in 2015. It improves on the complex callback pattern of the legacy XMLHttpRequest (XHR) by being Promise-based, allowing asynchronous HTTP communication to be handled more intuitively. It is currently supported natively in all modern browsers and in Node.js 18+.

The fetch() function takes a Request object or a URL as an argument and creates a Promise that returns a Response object. The Response object provides methods for parsing the response body into various forms (JSON, text, blob, arrayBuffer). It also supports stream-based processing, so it is used for downloading large files and processing real-time data as well.

A key characteristic of the Fetch API is that, by default, it does not throw HTTP errors (4xx, 5xx) as exceptions. Only network failures are rejected, and the HTTP status code must be checked directly with response.ok or response.status. This design makes it possible to read error messages included in the response body, but an explicit status check is essential.

When used together with AbortController, an in-progress request can be canceled, so unnecessary requests can be stopped when the user leaves the page or the search term changes. In addition, options such as credentials, mode, and cache allow fine-grained control over cookie transmission, CORS behavior, and cache policy.

πŸ’» Code Example

// κΈ°λ³Έ GET μš”μ²­
const response = await fetch('/api/users');
if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();

// POST μš”μ²­ with JSON body
const newUser = await fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'κΉ€μ² μˆ˜', email: 'kim@example.com' }),
});

// 인증 토큰과 ν•¨κ»˜ μš”μ²­
const authResponse = await fetch('/api/profile', {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
  credentials: 'include', // μΏ ν‚€ 포함
});

// AbortController둜 μš”μ²­ μ·¨μ†Œ
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

try {
  const data = await fetch('/api/slow-endpoint', {
    signal: controller.signal,
  });
  clearTimeout(timeoutId);
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('μš”μ²­μ΄ νƒ€μž„μ•„μ›ƒλ˜μ—ˆμŠ΅λ‹ˆλ‹€');
  }
}

// 파일 μ—…λ‘œλ“œ with FormData
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('description', 'ν”„λ‘œν•„ 이미지');

await fetch('/api/upload', {
  method: 'POST',
  body: formData, // Content-Type μžλ™ μ„€μ •
});

// μž¬μ‚¬μš© κ°€λŠ₯ν•œ fetch wrapper
async function api(endpoint, options = {}) {
  const response = await fetch(`/api${endpoint}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({}));
    throw new Error(error.message || `HTTP ${response.status}`);
  }

  return response.json();
}

πŸ—£οΈ Examples of Practical Conversations

πŸ‘¨β€πŸ’» Junior developer
"I called an API with fetch, but error handling doesn't seem to work properly. I wrapped it in try-catch, but a 404 error doesn't go to the catch."
πŸ‘©β€πŸ’» Senior developer
"fetch only rejects on network errors. You need to check HTTP errors with response.ok. For the pattern, please throw explicitly with 'if (!response.ok) throw new Error(...)'. It's convenient to create a wrapper function that automatically throws errors, like axios does."
πŸ‘¨β€πŸ’Ό Technical interviewer
"What are the differences between fetch and axios, and in which situations would you choose each?"
πŸ‘¨β€πŸ’» Candidate
"fetch is browser-native, so the bundle size is 0, and it is sufficient in most cases. However, axios is more convenient for interceptors, automatic error handling, and request cancellation, and it also supports IE. For small projects, I create and use a fetch wrapper, and when a complex API layer is needed, I choose axios."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More