본문 바로가기
JavaScript

[JS]fetch()함수로 API 호출

by 갈잃자 2022. 11. 25.

fetch()를 사용하는 이유

  • fetch() 함수는 브라우저에서 내장된 함수이다.
  • request, axios, jQuery와 같은 라이브러리를 사용하지 않아도 되므로, 불필요한 낭비를 줄일 수 있다.

fetch() 사용법

fetch(url, options)
	// 요청 성공시 response 객체를 받아 사용
	.then((response) => console.log("response:", response))
	// 요청 실패시 error 객체를 받아 사용
	.catch((error) => console.log("error:", error))

단순 crud 관련 호출하는 방법

1. GET 호출(R)

  • url의 값을 읽을 때 사용되는 호출
  • fetch() 함수는 디폴트가 GET이므로 method Type을 작성할 필요가 없다.
  • GET 방식은 요청 전문을 받지 않기 때문에 옵션인자가 필요가 없다.
fetch("url")
					 //json 포맷시킴
  .then((response) => response.json())
  .then((data) => console.log(data));

//응답
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"
}

2. POST 호출(C)

  • body의 값을 전제로 data를 생성하는 method
  • POST 요청부턴 options 가 붙는데, 해당 options엔 method 형태와 headers, body가 들어간다.
fetch("url", {
  method: "POST",
  // Content-type: 응답하는 내용의 타입과 문자 포맷을 표현
  headers: {
    "Content-Type": "application/json",
  },
  // 명세서에 협의된 body를 넣음.
  body: {
    title: "Test",
    body: "I am testing!",
    userId: 1,
  },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

//응답
{title: 'Test', body: 'I am testing!', userId: 1, id: 101}

3. PUT 호출(U)

  • 데이터의 수정을 위해 사용되는 호출이다.
  • PUT 방식은 method 옵션을 PUT으로 설정하고 나머지는 POST 방식과 유사
fetch("url", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  // 명세서에 협의된 body를 넣음.
  body: JSON.stringify({
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

//응답
{title: "Test", body: "I am testing!", userId: 1, id: 1}

4. DELETE 호출(D)

  • 데이터 삭제를 위한 호출이다.
  • DELETE호출은 url값에 맞는 걸 지우기 때문에, headers와 body 가 필요없다.
fetch("url", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data));


//응답
{}

출처: https://www.daleseo.com/js-window-fetch/

 

[자바스크립트] fetch() 함수로 원격 API 호출하기

Engineering Blog by Dale Seo

www.daleseo.com

 

'JavaScript' 카테고리의 다른 글

js 동작원리 와 eventLoop  (0) 2023.05.09
동기와 비동기  (0) 2023.05.08
array(배열)을 변형시키는 내장함수들  (0) 2022.09.20
형변환, typeof  (0) 2022.09.18
삼항연산자  (0) 2022.09.17

댓글