본문 바로가기
📺 Front End/-- JS & ES6+

[Javascript] Fetch API로 구현하는 Ajax 비동기 통신

by Wonit 2021. 2. 26.

ajax

  • XMLHttpRequest 객체를 이용해서 웹 서버와 비동기로 통신하고, DOM 을 이용해서 웹 페이지를 동적으로 바꿔주는 프로그래밍 기법
  • Asynchronouse JavaScript XML
  • 현재 XML을 사용하는건 드물고 JSON을 사용
  • 페이지 새로고침 없이 특정 데이터만 리로드
  • 서버로부터 데이터를 받고 작업을 수행

ajax 구현하기

ajax를 구현하는 기술에는 여러 기술이 존재한다.

 

그 중에 대표적인 3가지에서 Fetch API에 대해서 알아보자.

  1. XMLHttpRequest
  2. Fetch API
  3. JQuery

Fetch API

Fetch API는 기본적으로 XMLHttpRequest 보다 더 강력하고 유연하다.


이벤트 기반인 XMLHttpRequest과는 달리 Fetch API는 Promise 기반으로 구성되어 있어 비동기 처리 프로그래밍 방식에 잘 맞는 형태이다.


그래서 then이나 catch 와 같은 체이닝으로 작성할 수 있다.


결국 이는 가독성에 큰 이점을 줬고, Async / Await 으로 비동기 콜백을 쉽게 벗어날 수 있기도 하다.


또한 Fetch API는 JS 기본 라이브러리기 때문에, JQuery와 같이 CDN 과 같은 다른 작업을 하지 않아도 바로 사용할 수 있다.

Fetch API의 기본 형태

앞서 말 했듯, Fetch API 는 Promise 기반이기 때문에 체이닝 형태로 사용될 수 있다.

 

다음은 thencatch로 체이닝을 한 형태이다.

fetch("http://server-ip.com")
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(JSON.stringify(myJson));
  })
  .catch((error) => {
    console.err(error);
  });

header 조작하기

서버와 통신을 할 때, HTTP 헤더를 조작하는 일은 필수적으로 진행되어야 한다.


Fetch API 에서도 header를 조작할 수 있는데, 다음과 같이 option 객체에 headers 에 들어갈 내용들을 지정하는 방법을 사용할 수 있다.

const option = {
  headers: {
    "Content-Type": "application/json",
  },
};

fetch("http://server-ip.com", option)
  .then((response) => {
    // 생략
  })
  .then((myJson) => {
    // 생략
  })
  .catch((error) => {
    // 생략
  });

Fetch API GET Method

Fetch API로 HTTP의 GET 메서드를 사용하여 데이터를 서버로 보내는 방법은 다음과 같다.

const option = {
  headers: {
    "Content-Type": "application/json",
  },
};

fetch("http://server-ip.com", option)
  .then((response) => {
    // 생략
  })
  .then((myJson) => {
    // 생략
  })
  .catch((error) => {
    // 생략
  });

Fetch API POST Method

Fetch API로 HTTP의 POST 메서드를 사용하여 데이터를 서버로 보내는 방법은 다음과 같다.

const myData = {
  id: 1,
  content: "content",
};

const option = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(myData),
};

fetch("http://server-ip.com", option).then((res) => {
  // 생략
});

Fetch API PUT Method

Fetch API로 HTTP의 PUT 메서드를 사용하여 데이터를 서버로 보내는 방법은 다음과 같다.

const myData = {
  id: 1,
  content: "content",
};

const option = {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(myData),
};

fetch("http://server-ip.com", option).then((res) => {
  // 생략
});

Fetch API DELETE Method

Fetch API로 HTTP의 DELETE 메서드를 사용하여 데이터를 서버로 보내는 방법은 다음과 같다.

const myData = { id: 1 };

const option = {
  method: "DELETE",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(myData),
};

fetch("http://server-ip.com", option).then((res) => {
  // 생략
});

댓글