React fetch

jaehan·2022년 5월 11일
0

React

목록 보기
4/33
post-thumbnail

React 애플리케이션에서 API를 사용하는 방법으로는 크게 AxiosFetch API가 있는데 현재 한이음 프로젝트에서 Fetch API를 사용했기 때문에 Fetch API에 대해 공부해 보겠다.

💻 fetch 란?

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

💡 fetch의 기본구조

fetch(url, [options])
url : 접근하고자 하는 url
[options] : 선택 매개변수(method나 header 지정가능)

options의 항목

  • method : 사용할 메소드를 선택 ('GET', 'POST', 'PUT', 'DELETE' )
  • headers : 헤더에 전달할 값 ( { 'content-Type': 'application/json' } )
  • body : 바디에 전달할 값 ( JSON.springfy(data) )
  • mode : 'cors' 등의 값을 설정 (cors, no-cors, same-origin)
  • credentials : 자격 증명을 위한 옵션 설정 (include, same-origin, omit)(default = same-origin)
  • cache : 캐쉬 사용 여부 (no-cache, reload, force-cache, only-if-cached)

fetch() 구조

fetch('api 주소')
.then(res => res.json())
.then(res => {
  // data를 응답 받은 후의 로직
});

fetch api는 Promise를 반환한다, 작업을 거친 이후에 Promise가 response의 인스턴스와 함께 이행상태가 된다.

response에는 Promise를 기반으로 하는 다양한 메소드가 존재한다.

  • res.text() : 응답을 읽고 텍스트를 반환한다.

  • res.json() : 응답을 JSON 형태로 파싱한다.

  • res.blob() : 응답을 Blob(타입이 있는 바이너리 데이터) 형태로 변환한다.


💡 method가 get인 경우

fetch에서 default method는 get이기 때문에 get method를 사용할 때는 명시를 안해줘도 된다

fetch('https://api.jh.com/user/3')
.then(res => res.json())
.then(res => {
  if (res.success) {
      console.log(`${res.user.name}` 님 반갑습니다!);
  }
});

💡 method가 post인 경우

fetch('https://api.js.com/user', {
    method: 'post',
    body: JSON.stringify({
        name: "jaehan",
        batch: 1
    })
  })
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        alert("저장 완료");
    }
  })

📌 post method시에는 option값에 method: 'post'를 꼭 해줘야 한다

✔️ fetch는 비동기적으로 처리되는 함수이고, 처리가 완료되기까지 시간이 오래걸리기 때문에 fetch가 끝나기도 전에 다른 함수가 먼저 실행될 수 있다. 그렇기 때문에 then을 써서 순서를 고정시키는 것이다.

0개의 댓글