JS fetch()
발행: (2026년 5월 6일 PM 02:06 GMT+9)
2 분 소요
원문: Dev.to
Source: Dev.to
fetch()란?
fetch()는 네트워크/HTTP 요청을 만들 때 사용하는 내장 함수입니다.- Promise를 반환합니다.
- Promise는 서버 응답을 나타내는 Response 객체와 함께 해결됩니다.
- 이후 요청 상태를 확인하고 응답 본문을 텍스트, JSON 등 다양한 형식으로 추출할 수 있습니다.
HTTP 메서드
- GET – 데이터 조회
- POST – 데이터 생성
- PUT – 데이터 업데이트
- DELETE – 데이터 삭제
문법
fetch(url, options)
url→ API 엔드포인트options→ 메서드, 헤더, 본문 등
fetch(url)을 호출하면 요청이 전송되고 Promise가 반환됩니다.
fetch(url)
.then(response => {
// response에는 상태(200, 404…), 헤더, 본문(아직 읽을 수 없음) 등이 포함됩니다.
});
본문 읽기
response.json() // 본문을 JavaScript 객체로 변환 (Promise 반환)
response.text() // 본문을 일반 텍스트로 반환 (Promise 반환)
기본 GET 요청
// JSON 데이터 가져오기
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err));
// 일반 텍스트 가져오기
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.text())
.then(data => console.log(data))
.catch(err => console.log(err));
오류 처리
fetch("https://jsonplaceholder.typicode.com/post")
.then(res => {
if (!res.ok) {
throw new Error("HTTP Error: " + res.status);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.log(err));