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.
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.
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.
// κΈ°λ³Έ 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();
}
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free