1. 소개
JavaScript는 웹 개발에서 가장 널리 사용되는 프로그래밍 언어 중 하나입니다. 그 많은 기능 중에서 Fetch API는 비동기 통신을 가능하게 하는 중요한 기능으로 주목을 받고 있습니다.
이 기사에서는 Fetch API를 기본부터 고급 사용법까지 자세히 설명합니다. 이를 이해하면 웹 애플리케이션에서 데이터 가져오기와 서버 통신을 더 원활하게 구현할 수 있습니다.
비동기 통신이란?
비동기 통신은 통신이 완료될 때까지 차단되지 않고 다른 처리를 계속하면서 서버와 데이터를 교환하는 방법입니다. 이는 사용자 인터페이스의 응답성을 향상시키고, 데이터를 처리할 때 좌절감을 줄이는 데 도움이 됩니다.
예를 들어, 사용자가 웹 페이지의 버튼을 클릭하여 데이터를 가져올 때 서버의 응답을 기다리지 않고 다른 작업을 계속할 수 있어 사용자 경험이 크게 향상됩니다.
Fetch API란?
Fetch API는 JavaScript에서 비동기 통신을 수행하기 위한 현대적인 인터페이스입니다. 전통적인 XMLHttpRequest (XHR)의 대안으로 도입되었으며, 간결한 구문과 유연한 구성을 제공합니다.
이 API를 사용하면 서버에서 데이터를 쉽게 가져오거나 서버로 데이터를 보내는 로직을 작성할 수 있습니다.
다음 섹션에서는 기본 Fetch API 사용법부터 실전적인 예제까지 단계별로 소개하겠습니다.
2. Fetch API란?
Fetch API는 JavaScript에서 비동기 통신을 수행하기 위한 최신 표준 인터페이스입니다. 이 섹션에서는 기본 역할과 전통적인 접근 방식과의 차이점을 설명합니다.
Fetch API 개요
Fetch API는 네트워크를 통해 리소스를 가져오도록 설계되었습니다.
이로 인해 웹 애플리케이션이 서버와 쉽게 통신할 수 있습니다.
주요 특징
- Promise 기반 : 콜백 함수에 의존할 필요가 없어 더 읽기 쉬운 코드를 작성할 수 있습니다.
- 간결한 구문 : XMLHttpRequest에 비해 코드 양을 크게 줄일 수 있습니다.
- 높은 유연성 : 요청과 응답을 세부적으로 사용자 지정할 수 있습니다.
- 현대적인 설계 : 현대 JavaScript 기능과 잘 작동하여 유지보수 가능한 코드를 가능하게 합니다.
아래는 Fetch API를 사용하는 기본 예제입니다.
fetch('https://api.example.com/data')
.then(response => response.json()) // Convert to JSON
.then(data => console.log(data)) // Output the data
.catch(error => console.error('Error:', error)); // Error handling
이 코드는 지정된 URL에서 데이터를 가져와 JSON으로 변환한 후 콘솔에 표시합니다. 오류가 발생하면 오류 메시지를 출력합니다.
전통적인 XMLHttpRequest와의 차이점
Fetch API는 널리 사용되는 XMLHttpRequest (XHR)를 대체하는 새로운 접근 방식입니다. 아래 표는 둘을 비교합니다.
| Feature | Fetch API | XMLHttpRequest |
|---|---|---|
| Code simplicity | Concise, readable syntax | Often complex with many callbacks |
| Asynchronous handling | Supports Promises and offers high flexibility | Requires callback functions |
| Stream processing | Native support | Requires additional handling |
| Working with JSON | Easy to handle | Requires explicit parsing |
| Error handling | Flexible and can be centralized | Often becomes complex |
보시다시피 Fetch API는 간결하고 현대적인 설계로 매력적입니다. 특히 Promise 기반이기 때문에 비동기 로직을 더 자연스럽게 작성할 수 있습니다.
요약
Fetch API는 JavaScript에서 비동기 통신을 위한 강력하고 사용하기 쉬운 도구입니다. 전통적인 XHR보다 구현이 간단하기 때문에 현대 웹 개발의 필수 기술이 되었습니다.
다음 섹션에서는 코드 예제와 함께 Fetch API의 구체적인 사용 패턴을 살펴보겠습니다.

3. Fetch API의 기본 사용법
이 섹션에서는 구체적인 코드 예제를 통해 Fetch API의 기본 사용법을 설명합니다. 주로 다음 사항을 다룹니다.
fetch()메서드의 구문과 기본 예제- GET 요청 구현 방법
- 응답 데이터 처리 방법
fetch() 메서드의 기본 구문
Fetch API를 사용하면 fetch() 메서드를 통해 서버에 요청을 보냅니다. 아래는 기본 구문입니다.
fetch(url, options)
.then(response => {
// Handle the response
})
.catch(error => {
// Handle errors
});
인수
- url : 요청이 전송되는 URL.
- options (optional): 메서드, 헤더, 본문 등을 포함하는 옵션 설정.
Return value
- Promise object : 비동기 처리 결과를 반환합니다.
How to implement a GET request
Fetch API의 가장 기본적인 사용은 GET 요청이며, 서버에서 데이터를 가져옵니다.
Example: Fetch JSON data
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network error');
}
return response.json(); // Retrieve data as JSON
})
.then(data => {
console.log(data); // Display the retrieved data
})
.catch(error => {
console.error('Error:', error); // Print an error log
});
How to process response data
Fetch API를 사용하면 다양한 형식의 응답 데이터를 처리할 수 있습니다. 아래는 일반적인 예시입니다.
- Retrieve text data
fetch('https://example.com/data.txt') .then(response => response.text()) // Retrieve data as text .then(data => console.log(data)) .catch(error => console.error('Error:', error));
- Retrieve binary data
fetch('https://example.com/image.jpg') .then(response => response.blob()) // Retrieve as binary data .then(blob => { const imgURL = URL.createObjectURL(blob); document.querySelector('img').src = imgURL; }) .catch(error => console.error('Error:', error));
- Retrieve header information
fetch('https://example.com/api') .then(response => { console.log(response.headers.get('Content-Type')); // Get a header value }) .catch(error => console.error('Error:', error));
Summary
여기서는 Fetch API를 사용한 기본 GET 요청과 응답 처리 방법을 다루었습니다.
Fetch API는 텍스트, JSON, 바이너리 데이터 등 다양한 유형의 데이터를 쉽게 가져올 수 있는 유연한 도구입니다. 이 기본 개념을 이해하면 오류 처리와 POST 요청을 포함한 다음 장에 적용하기가 쉬워집니다.
다음 섹션에서는 Fetch API를 사용한 오류 처리에 대해 자세히 설명합니다.
4. Error handling
이 섹션에서는 Fetch API 사용 시 오류 처리에 대해 설명합니다. 서버와 통신할 때 네트워크 오류나 응답 오류와 같은 다양한 문제가 발생할 수 있습니다. 이를 적절히 처리하면 사용자 경험을 향상시킬 수 있습니다.
Basics of error handling
Fetch API에서는 catch() 메서드를 사용해 네트워크 실패나 오류 응답과 같은 경우를 처리할 수 있습니다.
Basic error handling example
fetch('https://example.com/data')
.then(response => {
if (!response.ok) { // Check the response status code
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('An error occurred:', error)); // Error handling
Error handling with try…catch
Async/Await를 사용하면 더 깔끔하고 가독성 높은 코드를 작성할 수 있습니다. 이 경우 try...catch 문으로 오류를 처리합니다.
Example: Error handling with Async/Await
async function fetchData() {
try {
const response = await fetch('https://example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('An error occurred:', error);
}
}
fetchData();
Implementing timeouts
Fetch API는 기본적으로 내장 타임아웃 기능을 제공하지 않습니다. 하지만 타임아웃을 구현하면 느린 응답을 적절히 처리할 수 있습니다.
Example: Implementing a timeout
function fetchWithTimeout(url, timeout = 5000) {
return Promise.race([
fetch(url),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), timeout)
),
]);
}
fetchWithTimeout('https://example.com/data', 5000)
.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('An error occurred:', error));
Detecting network errors
A network error refers to cases where the server cannot be reached or the connection is interrupted. With the Fetch API, these errors can also be detected with catch().
Example: Handling a network error
fetch('https://invalid-url.com/data')
.then(response => response.json())
.catch(error => console.error('Network error:', error.message));
Summary
In this section, we introduced error handling with the Fetch API, from basics to more advanced patterns.
Key takeaways
- Check response status codes and implement error handling
- Simplify error handling with Async/Await
- Handle slow responses by implementing timeouts
Error handling is critical for improving the user experience. In the next section, we’ll explain POST requests for sending data to a server.

5. Sending POST requests
In this section, we explain how to send POST requests with the Fetch API to send data to a server. We’ll cover practical examples such as sending form data and JSON.
Basic syntax for POST requests
You can implement a POST request in the Fetch API by providing an options object as the second argument to the fetch() method.
Basic syntax
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Example: Sending JSON data
Below is an example of sending user information in JSON format.
const userData = {
name: 'Taro Yamada',
email: 'yamada@example.com',
};
fetch('https://example.com/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Example: Sending form data
To send form data, use the FormData object.
const formData = new FormData();
formData.append('username', 'yamada');
formData.append('file', fileInput.files[0]);
fetch('https://example.com/upload', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log('Upload success:', data))
.catch(error => console.error('Error:', error));
Example: Requests with authentication information
When sending data along with authentication information (for example, a token), add the auth data to the request headers.
fetch('https://example.com/api/protected', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
body: JSON.stringify({ message: 'Hello!' }),
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Error handling for POST requests
For POST requests, you can add error handling like the following to deal with network issues or server-side problems.
async function postData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
console.log('Success:', result);
} catch (error) {
console.error('An error occurred:', error.message);
}
}
postData('https://example.com/api/messages', { text: 'Hello!' });
Summary
In this section, we explained the basics and practical usage of POST requests using the Fetch API.
Key takeaways
- How to send JSON data and form data
- How to implement requests with authentication information
- How to strengthen error handling
POST requests are essential for two-way communication with servers. In the next section, we’ll explain customization options for the Fetch API in detail.
6. Other option settings
In this section, we explain various option settings you can specify as the second argument to the Fetch API. By using these, you can easily customize requests and manage authentication information.
Basic option syntax
Fetch API options are specified as an object in the second argument.
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
body: JSON.stringify(data),
credentials: 'include',
mode: 'cors',
cache: 'no-cache',
redirect: 'follow',
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Details of each option
method(HTTP method)
- Specifies the HTTP method (for example: GET, POST, PUT, DELETE).
- The default is
GET.
headers(headers)
- Specifies request headers.
- Used to define the data format or add authentication information.
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_ACCESS_TOKEN', }
body(sending data)
- Used to send data to the server with POST or PUT methods.
credentials(managing credentials)
- Controls whether credentials (cookies or HTTP authentication data) are sent.
| Value | Description |
|---|---|
omit | Do not send credentials (default) |
same-origin | Send credentials only for same-origin requests |
include | Send credentials even for cross-origin requests |
mode(CORS policy)
- Controls cross-origin request behavior.
| Value | Description |
|---|---|
cors | Allow cross-origin requests (default) |
no-cors | Allow only simple requests (limited) |
same-origin | Allow requests only to the same origin |
cache(cache control)
- Controls how request caching is used.
| Value | Description |
|---|---|
default | Use the browser’s default cache settings |
no-store | Do not use cache; always make a new request |
reload | Ignore cache and make a new request |
redirect(redirect handling)
- Specifies how redirects are handled.
| Value | Description |
|---|---|
follow | Automatically follow redirects (default) |
error | Treat redirects as errors |
manual | Handle redirects manually (controllable in code) |
Advanced customization example
Below is an example that combines multiple options.
fetch('https://example.com/api/resource', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
body: JSON.stringify({ message: 'Hello!' }),
credentials: 'include',
mode: 'cors',
cache: 'no-cache',
redirect: 'follow',
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Summary
In this section, we explained various Fetch API option settings in detail.
Key takeaways
- How to customize headers and credentials
- Fine-grained settings such as CORS and cache control
- Advanced patterns for redirects and error handling
In the next section, we’ll introduce concrete examples of how to use the Fetch API in practice.

7. Practical examples of using the Fetch API
In this section, we explain how you can use the Fetch API in real projects with concrete examples. Through practical scenarios, you’ll build real-world Fetch API skills.
Displaying a list of API data
A common use case in web applications is fetching data from an external API and displaying it as a list. In the example below, we fetch post data from the JSONPlaceholder API and display it as an HTML list.
Code example
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(posts => {
const list = document.getElementById('post-list');
posts.forEach(post => {
const listItem = document.createElement('li');
listItem.textContent = `${post.id}: ${post.title}`;
list.appendChild(listItem);
});
})
.catch(error => console.error('Error:', error));
HTML example
<ul id="post-list"></ul>
Submitting a form and registering data
This is an example of registering data from a form input to a server.
Code example
const form = document.getElementById('user-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
};
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
console.log('Registration successful:', result);
alert('The user has been registered!');
} catch (error) {
console.error('Error:', error);
alert('An error occurred.');
}
});
HTML example
<form id="user-form">
<input type="text" id="name" placeholder="Name" required />
<input type="email" id="email" placeholder="Email address" required />
<button type="submit">Register</button>
</form>
File upload
The Fetch API can also handle file uploads. Below is an example of uploading an image file to a server.
Code example
const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');
uploadButton.addEventListener('click', async () => {
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('https://example.com/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
console.log('Upload successful:', result);
alert('The file has been uploaded!');
} catch (error) {
console.error('Error:', error);
alert('Upload failed.');
}
});
HTML example
<input type="file" id="file-input" />
<button id="upload-button">Upload</button>
Summary
In this section, we introduced practical examples using the Fetch API.
Key takeaways
- Creating a dynamic list by displaying API data
- Implementing form submission and data registration
- Implementing file uploads and search functionality
By using these examples as references, you can build interactive web applications powered by the Fetch API. In the next section, we’ll summarize the entire article and introduce learning resources for your next steps.
8. Summary
In this article, we explained JavaScript’s Fetch API systematically—from the basics to practical use. The Fetch API is a powerful tool that enables asynchronous communication concisely and efficiently, making it essential for modern web application development.
Review of what you learned
- Overview and features of the Fetch API
- The Fetch API is Promise-based, allowing concise and flexible code.
- Compared to traditional XMLHttpRequest, the syntax is simpler and easier to maintain.
- Basic usage and error handling
- Basic syntax for fetching data with GET requests.
- By adding error handling and timeout processing, you can implement more robust code.
- Sending data with POST requests
- JSON 데이터와 폼 데이터를 전송하는 예시.
- 인증 정보와 커스텀 헤더를 추가하는 방법을 배웠습니다.
- 옵션 설정을 효과적으로 활용하기
- 캐시 제어, CORS 설정, 자격 증명 관리 등 유연한 커스터마이징 방법을 소개했습니다.
- 실전 예시
- 리스트 표시, 폼 제출, 파일 업로드, 검색 기능 등 예시를 통해 실제 사용법을 배웠습니다.
Fetch API의 장점 및 유의사항
장점
- 코드가 간결하고 가독성이 높습니다.
- Promise와 Async/Await와 잘 어울려 최신 JavaScript 문법과 쉽게 결합할 수 있습니다.
- JSON, 바이너리 데이터, 스트림 등 다양한 데이터 형식을 지원합니다.
유의사항
- 기본적으로 타임아웃 기능이 없으므로 직접 구현해야 할 수 있습니다.
- 구형 브라우저(예: Internet Explorer)에서는 지원되지 않으므로 필요에 따라 폴리필이나 대안을 고려해야 합니다.
다음 단계 학습 자료
Fetch API에 대한 이해를 깊게 하려면 아래 공식 문서와 자료를 활용하세요.
- MDN Web Docs (Fetch API) https://developer.mozilla.org/ja/docs/Web/API/Fetch_API
- MDN의 JavaScript 문서 https://developer.mozilla.org/ja/docs/Web/JavaScript
- 샘플 프로젝트 및 코드 모음 GitHub이나 CodePen에서 Fetch API를 활용한 실제 프로젝트를 살펴보는 것도 도움이 됩니다.
마무리
Fetch API는 현대 JavaScript 기법을 사용해 서버와의 통신을 간단히 구현할 수 있게 해 주는 강력한 도구입니다. 이 글에서 배운 내용을 적용하면 보다 인터랙티브하고 풍부한 기능을 갖춘 웹 애플리케이션을 만들 수 있습니다.
웹 개발이 지속적으로 발전함에 따라 API 통합과 비동기 처리의 중요성은 더욱 커질 것입니다. Fetch API를 마스터하고 실전 역량을 강화하세요!
다음 단계
- 실제 API를 활용하는 프로젝트를 만들어 보세요.
- 커스텀 옵션을 사용해 보다 고급 요청 처리를 구현해 보세요.
- 서버‑사이드 백엔드와 연동되는 풀스택 애플리케이션을 구축해 도전해 보세요.
이로써 글을 마칩니다. Fetch API 학습이 여러분의 실력을 한층 더 끌어올리는 데 도움이 되길 바랍니다!


