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

권영균·2021년 3월 28일
0

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

설명: 유저를 저장한다.
base url: https://api.google.com
endpoint: /user
method: post
요청 body:
    {
        "name": string,
        "batch": number
    }

응답 body:
    {
        "success": boolean
    }

호출할때!!

fetch('https://api.google.com/user', {
    method: 'post',
    body: JSON.stringify({
        name: "yeri",
        batch: 1
    })
  })
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        alert("저장 완료");
    }
  })
  1. 두 번째 인자에 method와 body를 보내주어야 합니다.
  2. method는 post
  3. body는 JSON형태로 보내기 위해 JSON.stringfy() 함수에 객체를 인자로 전달하여 JSON형태로 변환했습니다.

post로 데이터를 보낼 때 JSON.stringfy를 항상 하다보니 axios는 굳이 감싸주지 않고 객체만 작성해도 되는 편리한 점이 있습니다. 이렇듯 axios는 소소하게 편한한 설정을 제공해주고, 요청과 응답에 대한 확장성 있는 기능을 만들 수 있습니다.

fetch() 함수 - method가 get인데 parameter를 전달해야 하는 경우

위의 get에서 3이라는 user id를 path로 넘겨주었습니다. 그런데 path 말고 query string으로 넘겨줘야 할 수도 있습니다.
언제는 path로 언제는 query string이고 할 수 있다는 말은 아니고, 예제이다 보니 같은 api를 사용했습니다. 데이터를 전달하는 방식 또한 백앤드 개발자에게 물어봐야 합니다.

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

호출!!

fetch('https://api.google.com/user?id=3')
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        console.log(`${res.user.name}` 님 환영합니다);
    }
  });
profile
GRIT(Growth(성장), Resilience(회복력), Intrinsic Motivation(내재적 동기), Tenacity(끈기))를 중시하는 프론트엔드 개발자입니다.

0개의 댓글