[JavaScript] Fetch API 정리

배똥회장·2022년 8월 5일

📝 기본 정리

  • fetch(url, options)
    - 첫번째 인자로 URL

    • 두번째 인자로 옵션 객체
    • Promise 타입의 객체를 반환
  • Promise 방식으로 구현

  • API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject


📌 데이터 조회 (GET)

  • fetch() 함수는 디폴트로 GET 방식으로 작동하고 GET 방식은 요청 전문을 받지 않기 때문에 옵션 인자가 필요가 없음

  • 응답이 이루어지면 응답받은 결과는 then( ) 함수의 인수로 전달 받음

fetch('주소')
.then((response) => response.json())
.then((json) => console.log(json));
  • 결과는 XMLHttpRequest로 조회했을 때와 동일함

✔ then() 함수 정리

  • 첫 번째 then( ) 함수는 서버 요처엥 대한 응답이 왔을 때 실행됨
    - 응답받은 데이터인 response는 문자열 형식이기 때문에 json( ) 함수를 호출하여 json 데이터로 변경을 실행

  • 두 번째 then( ) 함수는 response.json()으로 response가 json 데이터로 변경이 완료되면 실행
    - json 데이터로 변경된 데이터가 전달되며, 이 값을 console로 출력함


📌 데이터 생성 (POST)

fetch('주소', {
  method: 'POST',
  body: JSON.stringify({
	전달할 json 데이터
  }),
  headers: {
	헤더 값
  }
})
.then((response) => response.json())
.then((json) => console.log(json));
  • method에는 HTTP 요청 방법을 기록

  • HTTP 요청 방법, 헤더 값 등은 XMLHttpRequest와 동일


📌 데이터 수정 (PUT)

fetch('주소/:id', {
  method: 'POST',
  body: JSON.stringify({
	변경할 json 데이터
  }),
  headers: {
	헤더 값
  }
})
.then((response) => response.json())
.then((json) => console.log(json));
  • POST와 유사함

  • 주소/:id에서 특정 id의 값을 바꿔야하기 때문에 id를 입력하지 않으면 오류 발생.


📌 데이터 삭제 (DELETE)

fetch('주소/:id', {
  method: 'POST',
});

📌 파일 전송

  • FormData 객체 사용
  • FormData란?
    : HTML의 form 태그에 해당하는 form 필드와 그 값을 나타내는 일련의 키 - 값 쌍을 쉽게 생성할 수 있게 해주는 객체
let formData = new FormData();
let fileField = document.querySelector('input[type="file"');
formData.append('username', 'abc123');
formData.append('attachment', fileField.files[0]);
//url을 정확히 입력하지 않았기 때문에 이 코드 자체로는 오류를 리턴함
fetch('url', {
	method: 'POST',
	body: formData
})
.then(Response => response.json())
.catch(error => console.error('Error: ', error))
.then(response => console.log('Success: ', JSON.stringify(response)));

📝 참고 링크

https://www.daleseo.com/js-window-fetch/

profile
어쩌면 개발자

0개의 댓글