반응형
자바스크립트에서 서버와 통신할 때 가장 기본적이고 많이 쓰이는 방법이 fetch API입니다. fetch는 이전의 XMLHttpRequest보다 훨씬 직관적이며 Promise 기반으로 작성되어 코드 가독성이 높고 유지보수가 쉬운 장점이 있습니다.
이 글에서는 fetch를 사용한 기본 호출 → 응답 처리 → 에러 처리까지 초보자도 쉽게 이해할 수 있도록 정리합니다.
✅ 1. fetch 기본 사용법
📌 가장 간단한 GET 요청
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data));
- fetch()는 기본적으로 GET 요청을 보냅니다.
- response.json()은 응답을 JSON 객체로 변환합니다.
📌 async/await 버전
async function getPost() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log(data);
}
getPost();
✅ 2. 요청 옵션 설정하기
fetch(url, options) 형태로 옵션을 추가할 수 있습니다.
📌 POST 요청 예제
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
- method: 요청 메서드 지정 (POST, PUT, DELETE 등)
- headers: 요청 헤더 설정
- body: 전송할 데이터 (POST, PUT 등에서 사용)
✅ 3. 응답 상태 코드 처리
fetch 자체는 네트워크 에러만 reject합니다. 404나 500 같은 HTTP 에러는 정상적으로 resolve되므로 별도 체크가 필요합니다.
📌 응답 코드 체크
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP 에러! 상태: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('에러 발생:', error));
- response.ok는 상태 코드가 200~299 사이인지 여부를 반환합니다.
✅ 4. 네트워크 에러 및 타임아웃 처리
fetch는 기본적으로 타임아웃이 없습니다. 타임아웃을 설정하려면 AbortController를 사용합니다.
📌 AbortController로 타임아웃 구현
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://jsonplaceholder.typicode.com/posts/1', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.error('요청 시간이 초과되었습니다.');
} else {
console.error('다른 에러 발생:', error);
}
});
✅ 5. 고급: 공통 fetch 함수 만들기
실제 프로젝트에서는 중복을 줄이기 위해 공통 fetch 헬퍼를 만듭니다.
📌 fetchWrapper 예제
async function fetchWrapper(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP 상태 에러: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('요청 실패:', error);
throw error;
}
}
// 사용 예
fetchWrapper('https://jsonplaceholder.typicode.com/posts')
.then(data => console.log(data))
.catch(error => console.error('에러:', error));
✅ 결론
fetch는 단순한 GET/POST 요청부터 고급 에러 핸들링, 타임아웃 관리까지 매우 유연하게 활용할 수 있습니다. 현대 웹 개발에서는 axios 같은 라이브러리를 쓰기도 하지만, fetch만 잘 다뤄도 대부분의 REST API 호출을 문제없이 처리할 수 있습니다.
- 간단한 요청: 기본 fetch
- 에러 관리: .ok 체크 + .catch
- 고급 제어: AbortController로 타임아웃 설정
실제 프로젝트에서도 이 구조를 기반으로 확장해 나가는 것이 좋습니다.
반응형
'Programing > javascript' 카테고리의 다른 글
| 자바스크립트 실무 유틸 함수 시리즈 2 (0) | 2025.04.29 |
|---|---|
| 자바스크립트 실무 유틸 함수 시리즈 (0) | 2025.04.29 |
| DOM 조작 vs Virtual DOM (React 비교 포함) 정리 (0) | 2025.04.29 |
| JSON.stringify vs JSON.parse 제대로 이해하기 (0) | 2025.04.29 |
| 자바스크립트 Date 객체 소개, 예제, 그리고 심화 활용법 (1) | 2025.04.24 |
| moment.js 소개, 사용법, 그리고 심화 이해 (0) | 2025.04.24 |
| 자바스크립트 날짜 다루기: Date vs dayjs vs date-fns (0) | 2025.04.24 |
| 브라우저 저장소 정리: localStorage vs sessionStorage vs cookie (0) | 2025.04.24 |