JS Fetch API를 이용한 Ajax 통신

Fetch API 방식 이용한 Ajax

Ajax는 정통적으로 XMLHttpRequest() 객체를 사용하여 서버와 데이터를 교환합니다.

하지만 이 방식은 코드가 복잡하고 가독성이 좋지 않아 최신 기술인 fetch() 메서드를 통해 Ajax 통신하는 법에 대해 포스팅하겠습니다.

 

Fetch API 사용 장점

  • Fetch API는 Promise 기반으로 구성되어 있어 비동기 처리 방식에 적합한 형태입니다.
  • 체이닝 방식으로 작성 가능하기 때문에 가독성이 좋습니다.
  • Fetch API는 JavaScript 기본 기능이기 때문에 JQuery 같은 라이브러리를 가져다 쓰지 않기 때문에 가볍습니다.

Fetch 문법 사용법

 
      fetch("URL", option)
        .then((response) => response.text())
        .then((text) => console.log(text))
        .catch((err) => console.log("Fetch Error", err));
 
  • 첫 번째 매개변수: 요청할 URL
  • 두 번째 매개변수: 선택 매개변수
    • 사용할 HTTP 메서드, Headers, Body 등 정의 (생략 가능)
    • Default: GET 방식
  • 작동 순서
    • fetch()를 통해 URL에 요청을 보내고, 응답 객체(Response 객체)를 받음
    • 첫 번째 then에서 응답을 받고, res.text() 메서드로 파싱한 text 값 리턴
    • 다음 then에서 리턴받은 text값을 받고, 처리 수행

 

Response 객체

fetch()를 통해 요청을 보내고, 응답(Response 객체)을 받으면. then에서 함수의 인자에 담기게 됩니다. 이 Response 객체는 여러가지 정보를 갖고 있습니다.

  • response.status – HTTP 상태 코드
  • response.ok – HTTP 상태 코드가 200과 299 사이일 경우 true
  • response.body ㅡ 내용
  • response.text() – 응답을 읽고 텍스트를 반환
  • response.json() – 응답을 JSON 형태로 파싱
  • response.formData() – 응답을 FormData 객체 형태로 반환
  • response.blob() – 응답을 Blob(타입이 있는 바이너리 데이터) 형태로 반환
  • response.arrayBuffer() – 응답을 ArrayBuffer(바이너리 데이터를 로우 레벨 형식으로 표현한 것) 형태로 반환

Fetch HTTP 메서드 사용 예제

GET 방식 (Default)

fetch("URL/user/1") 
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((err) => console.log("Fetch Error", err))

 

POST 방식

fetch("URL/user", {
  method: "POST",                         // POST
  headers: {
    "Content-Type": "application/json",   // JSON 포맷 사용함
  },
  body: JSON.stringify({                  // 객체 -> JSON
	name: "Kim",
	age: 25,
  	city: "Seoul",
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

 

PUT 방식

fetch("URL/user", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    city: "Seoul"
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

 

DELETE 방식

fetch("URL/user/1", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data))

 

PATCH 방식

fetch("URL/user/1", {
  method: "PATCH",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    city: "Seoul"
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

 


async & await 문법 + Fetch API

fetch()가 반환하는 Response 객체는 Promise 객체이기 떄문에, async & await 문법을 사용할 수 있습니다.

fetch("URL/user", option)
	.then(res => res.text())
	.then(text => console.log(text));
    
/**
 * await은 async() 안에만 쓸 수 있기 때문에, 익명 async 함수를 바로 실행합니다.
 */
(async () => {
  let res = await fetch("URL/user", option);
  let text = await res.text();
  console.log(text);
})()

 


Fetch 모듈화

Fetch HTTP 메서드 사용 예제를 보면, 똑같은 코드가 중복해서 나타납니다. 한 두번 fetch() 메서드를 만들어 사용할 때는 굳이 모듈화하지 않아도 되지만, 여러 번 사용할 일이 있으면 모듈화하는 것이 더욱 효율적입니다.

 

Fetch 모듈화 예시 - POST 요청


      async function post(host, path, body, headers = {}) {
        const url = `https://${host}/${path}`;
        const options = {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...headers,
          },
          body: JSON.stringify(body),
        };
        const res = await fetch(url, options);
        const data = await res.json();
        if (res.ok) {
          return data;
        } else {
          throw Error(data);
        }
      }

      post("URL", "user", {
        name: "Kim",
        age: 25,
        city: "Seoul",
      })
        .then((data) => console.log(data))
        .catch((error) => console.log(error));