fetch API — 서버와 데이터 주고받기
이 토픽을 마치면
fetch로 서버에 요청을 보내고 응답을 처리하는 기본 패턴을 알게 됩니다.
fetch란
fetch는 브라우저에 내장된 HTTP 요청 함수입니다. 서버에 데이터를 요청하거나 보낼 때 씁니다. Promise를 반환하므로 async/await와 함께 씁니다.
javascript
const response = await fetch("/api/users");
const data = await response.json();
console.log(data);세 단계입니다: 요청 보내기 → 응답 받기 → 데이터 파싱.
GET 요청
데이터를 가져올 때 씁니다. 기본값이 GET이라 따로 지정할 필요 없습니다:
javascript
const res = await fetch("/api/users");
const users = await res.json();쿼리 파라미터가 필요하면 URL에 붙입니다:
javascript
const res = await fetch("/api/users?page=2&limit=10");POST 요청
데이터를 보낼 때 씁니다:
javascript
const res = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com",
}),
});
const created = await res.json();method, headers, body를 두 번째 인자로 넘깁니다. body에는 JSON.stringify로 변환한 문자열을 넣습니다.
응답 상태 확인
fetch는 HTTP 에러(404, 500)에서도 에러를 던지지 않습니다. 네트워크 자체가 실패했을 때만 에러를 던집니다.
javascript
const res = await fetch("/api/users/999");
console.log(res.status); // 404
console.log(res.ok); // false (status가 200-299 범위 밖)그래서 수동으로 확인해야 합니다:
javascript
const res = await fetch("/api/users");
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
const data = await res.json();에러 처리 패턴
javascript
async function fetchUsers() {
try {
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (error) {
if (error instanceof TypeError) {
console.log("네트워크 연결 실패");
} else {
console.log("요청 실패:", error.message);
}
return [];
}
}TypeError는 네트워크 자체가 안 될 때 발생합니다 (서버 다운, 오프라인).
응답 데이터 형식
javascript
const json = await res.json(); // JSON → 객체
const text = await res.text(); // 텍스트
const blob = await res.blob(); // 바이너리 (이미지 등).json(), .text(), .blob() 중 하나만 호출할 수 있습니다. 한 번 읽은 응답 body는 다시 읽을 수 없습니다.
핵심
fetch는 브라우저 내장 HTTP 요청 함수이며 Promise를 반환합니다. HTTP 에러(404, 500)에서 자동으로 에러를 던지지 않으므로res.ok를 확인해야 합니다. GET은 데이터 조회, POST는 데이터 전송에 사용합니다.