fetch 함수 사용하기

Seokho·2021년 12월 23일
0

fetch 함수의 기본구조

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

method 'post'

  • fetch()의 기본은 get이기 때문에 아무것도 작성하지 않아도 get으로 호출되지만, post인 경우에는 fetch() 함수에 method 정보를 인자로 넘겨주어야 합니다!
const submitUserInfoLogin = () => {
    fetch('http://10.58.3.111:8000/users/login', {
      method: 'POST',
      body: JSON.stringify({
        email: idText,
        password: pwText,
      }),
    })
      .then(res => res.json())
      .then(result => {
        if (result.MESSAGE === 'SUCCESS') {
          goTomain();
        }
      });
    // .then(result => console.log('결과: ', result));
  };

method 'get'

  • fetch() 함수에서 default method는 get입니다. API 명세가 아래와 같다면, 두번째 코드와 같이 호출할 수 있다.
useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((result) => setMonsters(result));
  }, []);

💡 동기 & 비동기에 대해 더 공부해야 함!

profile
같이의 가치를 소중하게 생각하는, 프론트엔드 개발자 이석호 입니다.

0개의 댓글