20. fetch()

김해준's avatar
Jan 22, 2026
20. fetch()
fetch() 메서드는 HTTP 요청을 보내고 응답을 받기 위한 API이며, 기본 형태는 다음과 같다.
fetch(url, options)

1. fetch() 파라미터 구조

파라미터
필수
설명
url
✅
요청할 서버 주소
options
❌
요청 설정 객체 (method, headers 등)

2. 첫 번째 파라미터: URL

fetch("https://api.example.com/users")
  • 문자열(String)
  • API 주소 또는 파일 경로

3. 두 번째 파라미터: options 객체

형식:
{ method:"GET", headers: {}, body: {}, mode:"cors", credentials:"include", cache:"no-cache" }

4. 주요 options 속성 정리


✅ method

HTTP 메서드
method:"GET" |"POST" |"PUT" |"DELETE" |"PATCH"
기본값: "GET"

✅ headers

요청 헤더
headers: { "Content-Type":"application/json", "Authorization":"Bearer token" }

✅ body

전송할 데이터 (POST/PUT)
body:JSON.stringify({name:"apple" })
⚠️ GET 요청에는 body 사용 불가

✅ mode

CORS 설정
mode:"cors" |"no-cors" |"same-origin"
기본값: "cors"

✅ credentials

쿠키 전송 여부
credentials:"include" |"same-origin" |"omit"

✅ cache

캐시 정책
cache:"default" |"no-cache" |"reload"

✅ signal (AbortController)

요청 취소용
signal: controller.signal

5. 가장 기본적인 사용 예제 (GET)

fetch("https://api.example.com/data") .then(res => res.json()) .then(data =>console.log(data));

6. POST 요청 예제

fetch("https://api.example.com/data", { method:"POST", headers: { "Content-Type":"application/json" }, body:JSON.stringify({ name:"사과", price:1000 }) });

7. 전체 옵션 예시

fetch("https://api.example.com/data", { method:"POST", headers: { "Content-Type":"application/json", "Authorization":"Bearer token" }, body:JSON.stringify({id:1 }), mode:"cors", credentials:"include", cache:"no-cache" });

8. 요약

fetch(url, options)
url = 요청 주소
options = 요청 방식 + 데이터 + 설정
options의 method는 디폴트값이 GET
Share article