Fetch API

HoJJANG94·2023년 2월 26일
0

JAVASCRIPT 내장 API - Fetch

리액트나 바닐라 자바스크립트에서 api를 통신할때 axios / fetch를 주로 사용하고 있었다.
뜬금없이 혼자 구글링없이 통신 + 화면 출력 + 등등 만들어 보기 위해 fake api를 json 형태로 만들어 연습할 겸 해보았다.
< 아래 api.json - fake api 내용 >

{
  "todos": [
    {
      "id": 1,
      "content": "HTML",
      "completed": true
    },
    {
      "id": 2,
      "content": "CSS3",
      "completed": true
    },
    {
      "id": 3,
      "content": "JAVASCRIPT",
      "completed": true
    },
  ]
}

이렇게 api를 간단하게 만들어 통신하기 위해 , 주로 GET 방식을 많이 썼었기에 , 간단하게

fetch.(url주소)
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err)) => console.log(err))

이러한 방식으로 사용하곤 했다.
물론 crud 작업을 위해 GET / POST / PUT / DELETE 다 써보았고, 프로젝트에도 사용했으며 방법 역시 어느정도 알고있다. 그러나 근래에 다른 공부를 하다 다시끔 연습하려 하니 fetch에 두번째 parameter 에 들어가는 문법이 가물해서 정리할겸 찾아보았다.

fetch(url주소, {
 1) method: "POST", 
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
 2) headers: { 
    "Content-Type": "application/json",  
  },
 3) body: JSON.stringify({
 4)	...?? 
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

간단하게 1,2,3 번호순으로 지정해둔 곳을 보면
1) GET & POST & PUT & DELETE (메소드) 즉 내가 사용할 메소드를 지정
2) headers에 json포맷을 사용한다고 알려주는 역할 (Content-Type 지정)
3) body에서 요청 전문을 JSON 포맷으로 넣어주도록 요청
4) method가 POST니까 생성할 키 밸류값 넣기

이러한 형식으로 사용 할 수 있다. 예외로 DELETE 같은 경우에는 보낼 데이터가 없기에
2)과 3)번 즉 headers, body 는 생략해도 된다.
고로 fakeapi를 이용해 만들어 본 것을 예시로 들면

GET

async function getApi() {
  await fetch("http://localhost:5000/todos")
    .then((res) => res.json())
    .then((data) => {
      try {
        data.map((item) => {
          const li = document.createElement("li");
          li.innerHTML = 
          `<div class="box">
          <span>${item.content}</span>
          <span>${item.completed}</span>
          </div>`;
          body.appendChild(li);
        });
      } catch (error) {
        alert(error.name);
      }
    });
}

POST

async function postApi() {
  await fetch("http://localhost:5000/todos", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      content: text.value,
      completed: false,
    }),
  })
    .then((res) => res.json())
    .then((data) => {
      try {
        alert("보내기 성공!");
      } catch (error) {
        console.log(error);
      }
    });
}

PUT

async function putApi() {
  await fetch(`http://localhost:5000/todos}`, {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      content: "JAVASCRIPT",
      completed: true,
    }),
  })
    .then((res) => res.json())
    .then((data) => console.log(data));
}

DELETE

function delApi() {
  await fetch(`http://localhost:5000/todos}`, {
    method: "DELETE",
    })
    .then((res) => res.json())
    .then((data) => console.log(data));
}

기억이 안날때는 공식문서 또는 구글링을 통해 한번 짚고 넘어가야 안 까먹는 것 같다.
Fetch API를 본 김에 axios 통신도 다시한번 공부해볼 필요가 있는 것 같다.

  • 얕고 다양한 지식보다는 한개라도 기초를 제대로 다지는게 좋다 느껴진다.
  • React 도 javascript 기반이기에 jsx문법을 사용하기에 바닐라 javascript 공부는 필수인것 같다.
profile
안녕하세요 신입 프론트엔드 개발자 입니다.

0개의 댓글