fetch()함수 사용방법(1)

권영균·2021년 3월 28일
0

백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받습니다. 이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios 라이브러리를 사용할 수 있습니다.
참고로 Web API는 클라이언트 측에서 사용할 수 있는 자바스크립트 내장함수라고 생각하시면 됩니다.

fetch() 함수 기본

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

fetch() 함수 기본의 ES5의 함수 선언식

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

fetch() 함수 - method가 get인 경우

설명: 유저 정보를 가져온다.
base url: https://api.google.com
endpoint: /user/3
method: get
응답형태:
    {
        "success": boolean,
        "user": {
            "name": string,
            "batch": number
        }
    }

호출할때!!

fetch('https://api.google.com/user/3')
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        console.log(`${res.user.name}` 님 환영합니다);
    }
  });

리액트에서 구현할때!!

import React, { Component } from 'react';

class User extends Component {
  componentDidMount() {
    // user id가 props를 통해 넘어온다고 가정
    const { userId } = this.props;

    fetch(`https://api.google.com/user/${userId}`)
      .then(res => res.json())
      .then(res => {
        if (res.success) {
            console.log(`${res.user.name}` 님 환영합니다);
        }
      });
  }
}
profile
공감을 중요시하고 프론트엔드에 강점을 가진 개발자 권영균입니다.

0개의 댓글

관련 채용 정보