JS - fetch API

Leo·2021년 5월 8일
0

JavaScript

목록 보기
3/3
post-thumbnail

fetch API

브라우저에서 fetch 함수를 지원하기 이전에는 API 호출을 위해서 requestaxios와 같은 라이브러리들을 주로 사용해왔다. 하지만 요즘에는 이런 라이브러리의 도움 없이 브라우저에 내장된 fetch 함수를 사용해도 충분한 경우가 많기 때문에 오히려 라이브러리를 사용하는 것이 자바스크립트 번들(Bundle)의 크기만 늘려서 낭비가 될 수도 있다.

사용법

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error))
  • url: 접근하고자하는 URL
  • options: HTTP 방식(method), HTTP요청 헤더(headers), HTTP 요청 전문(body)등을 지정할 수 있고 디폴트 값은 GET 메서드이다.

응답 과정

  1. 클라이언트가 요청을 한 후에 서버로부터 응답 헤더를 받으면 fetch 호출 시에 반환받은 Promise가 내장 클래스인 Response의 인스턴스와 함께 준비 상태가 된다. (본문인 body 도착 전)
  2. 아래와 같은 추가 메서드를 호출해서 응답의 본문을 받는다.
    • response.text(): 응답을 읽고 텍스트로 반환
    • response.json(): 응답을 jSON으로 파싱
    • response.formData(): 응답을 FormData 객체 형태로 반환
    • response.blob(): 응답을 Blob(타입이 있는 바이너리 형태)으로 반환
    • response.arrayBuffer(): 응답을 arrayBuffer(바이너리를 로우 레벨 형식으로 표현)으로 반환

GET

GET 방식은 request body 부분이 필요 없기 때문에 따로 두 번째 매개 변수인 options가 필요없다.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .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"
}

POST

POST 방식은 method를 POST, headers 옵션을 JSON 포맷으로 지정해야하며 request body를 JSON으로 직렬화해서 body 옵션에 지정해줘야한다.

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Post",
    body: "Hello, Post",
    userId: 1,
  }),
}).then((response) => console.log(response))
  .then((data) => console.log(data))

결과

{title: "Post", body: "Hello, Post", userId: 1, id: 101}

PUT

PUT 방식은 POST 방식에서 method를 제외하고 차이가 없다.

fetch("https://jsonplaceholder.typicode.com/posts/1", {
  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))

결과

{title: "Post", body: "Hello, Post", userId: 1, id: 101}

DELETE

fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data))

결과

{}

참조

0개의 댓글