Fetch API

Hunter Joe·2025년 6월 24일

Fetch API 구현 예제

// POST 메서드 구현 예제
async function postData(url = "", data = {}) {
  // 옵션 기본 값은 *로 강조
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE 등
    mode: "cors", // no-cors, *cors, same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, *follow, error
    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
  });
  return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}

postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});

method

Default : GET

GET
POST 
PUT 
PATCH 
DELETE

mode

Default : cors

no-cors 
cors
same-origin 

mode: "no-cors"를 지정하면 요청에 사용할 수 있는 헤더가 다음 목록으로 제한

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type 값으로는
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

cache

Default : same-origin

include
same-origin
omit

headers

Content-Type: "application/json"
Content-Type: "application/x-www-form-urlencoded"
Content-Type: "multipart/form-data"
Content-Type: "text/plain"

redirect

Default : follow

manual
follow
error

referrerPolicy

Default : no-referrer-when-downgrade

no-referrer
no-referrer-when-downgrade
origin
origin-when-cross-origin
same-origin
strict-origin
strict-origin-when-cross-origin
unsafe-url

자격 증명을 포함한 요청 전송

Default : same-origin

fetch("https://example.com", {
  credentials: "include", // include, same-origin, omit 
});

참고자료

https://developer.mozilla.org/ko/docs/Web/API/Fetch_API

profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글