Fetch API란?

경규혁·2023년 5월 19일
0

Fetch를 알아보기전에 AJAX란?

Ajax의 경우 자바스크립트에서 웹 페이지를 부분적으로 바꾸고 싶어 만들어진 라이브러리다. 쉽게 말하면 바뀌어야 될 웹페이지만 바뀌고 바뀌지 않아야 할 웹페이지는 그대로 내버려 두도록 도와주는 라이브러리다.

Fetch란?

fetch 메서드는 JavaScript에서 서버로 네트워크 요청을 보내고 응답을 받을 수 있도록 해주는 메서드이다.

Fetch API의 기본적인 구조

fetch(url, options)
  .then((response) => console.log("response:", response)) 
  .catch((error) => console.log("error:", error))

첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고 Promise 타입의 객체를 반환한다.
반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject한다.

// 예시
fetch(`http:// ~~~~ `)
  .then((response) => response.json()) // 데이터 타입 결정
  .then((json)=>console.log(json.data.movies)); // 데이터 전달 받음

Http Method 종류

HTTP Method를 통해 해당 자원에 대한 CRUD Operation을 적용하여 아래와 같이 사용한다.

Create: 데이터 생성 (POST)
Read: 데이터 조회 (GET)
Update: 데이터 수정 (PUT)
Delete: 데이터 삭제 (DELETE)

// GET 방식
fetch('https://api.example.com/data', {
  method: 'GET'
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log('Error:', error);
  });

// POST 방식
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log('Error:', error);
  });
  • headers : 요청 헤더에 대한 정보를 나타낸다.
  • body : 요청을 보내는 데이터를 나타낸다. 여러 가지 자료형을 대입할 수 있다.

// PUT 방식
fetch('https://api.example.com/data', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log('Error:', error);
  });

// DELETE 방식
fetch('https://api.example.com/data', {
  method: 'DELETE'
})
  .then(response => {
    if (response.ok) {
      console.log('Data deleted successfully');
    } else {
      console.log('Error:', response.statusText);
    }
  })
  .catch(error => {
    console.log('Error:', error);
  });
profile
갓생살기 기원!

0개의 댓글