프리랜서 웹디자이너 웹퍼블리셔RELATION

[ js] fetch

2025.09.18
출처 이동

fetch()
- 브리우져 함수, 익스플로러 지원X 
fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환합니다.
반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject합니다.
옵션(options) 객체에는 HTTP 방식(method), HTTP 요청 헤더(headers), HTTP 요청 전문(body) 등을 설정해줄 수 있습니다. 응답(response) 객체로 부터는 HTTP 응답 상태(status), HTTP 응답 헤더(headers), HTTP 응답 전문(body) 등을 읽어올 수 있습니다.
fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));


GET(default)
fetch("URL").then((response) =>
  console.log(response)
);

POST
fetch("URL", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({  /* param */
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
}).then((response) => console.log(response));

PUT(Update)
fetch("url", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));
답글쓰기 전체목록

이 포스트 공유하기

  • 페이스북에 공유하기
  • 트위터에 공유하기
  • 네이버 블로그 카페에 공유하기
  • 네이버 밴드에 공유하기

코멘트 쓰기

코멘트를 입력해주세요
LOGIN JOIN