[Ajax] Fetch API

이다혜·2022년 8월 24일
post-thumbnail

1. Fetch란?


클라이언트에서 서버로 비동기통신을 하기 위해 사용하는 API

네트워크 통신을 포함한 리소스 취득을 위한 인터페이스 정의

Ajax의 방식중 하나

2. Fetch 함수 구조


fetch('url', {
	Request 설정 옵션
    })
.then('함수')
.catch('에러 작업');
  • url : 접근하고자 하는 url 주소
  • opthion
    • mothod : 요청 방식
      GET, POST, PUT, DELETE ...
    • headers : API 요청시 파라미터 값 설정
      Content-type: application/json
    • body : 전달하는 데이터 형태
      JSON.stringify(data)
fetch(url, {
	method: 'POST',
    headers: {
    	'Content-type': 'application/json'
      // 데이터를 json 형태로 보내겠다.
    },
    body: JSON.stringify(data)
  	// 전달한 데이터를 json문자열로 변환
});

3. Fetch함수 구현해보기


3.1 GET: 존재하는 자원 요청

fetch(url) // fetch는 promise를 반환
  .then((response) => response.json())//Object화 시켜줌
  .then((data) => console.log(data))
  • response 객체가 제공하는 json() 메소드를 호출하면 응response 객체로부터 JSON 형태의 데이터를 JS 객체로 변환하여 얻을 수 있다.

  • fetch 함수의 디폴트는 GET 방식으로 옵션 인자가 필요 없다.

3.2 POST: 새로운 자원 등록 요청

fetch(url, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data)
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  • headers에 json 형식임을 알려주지 않으면 서버에서 데이터를 읽지 못하는 문제 발생

3.3 PUT: 존재하는 자원 변경 요청

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

3.4 DELETE: 존재하는 자원 삭제 요청

fetch(url, {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  • 전송할 데이터가 없으므로 body가 필요하지 않다.

0개의 댓글