백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받는다. 이 때 자바스크립트 Web API fetch()함수를 쓰거나 axios 라이브러리를 사용할 수 있다.
-> 여기서 Web API는 클라이언트 측에서 사용할 수 있는 자바스크립트 내장함수이다.
1. fetch() 함수
fetch('api 주소')
.then(res => res.json())
.then(res => {
// data를 응답 받은 후의 로직
});
위의 형태는 각각의 단계가 무엇을 뜻하는지 명확히 알아야 한다. 위의 함수는 화살표 함수로 몸통을 줄인 코드 이다. ES5의 함수 선언식으로 바꿨을 떄 어떤 모양인지 확인해 보자.
fetch('api 주소')
.then(function(res) {
return res.json();
})
.then(function(res) {
//data를 응답 받은 후의 로직
});
2. fetch()함수 - method가 get인 경우
fetch()함수에서 default method는 get이다. 그렇기에 위의 코드는 get으로 호출 한 것. 예를 들어 아래와 같은 api명세서를 보고 fetch()로 바꾼다면,
설명: 유저 정보를 가져온다.
base url: https://api.googl.com
endpoint: /user/3
method: get
응답형태:
{
"success": boolean,
"user": {
"name": string,
"batch": number
}
}
->
fetch('https://api.googl.com/user/3')//api 주소를 상황에 맞게 유동적으로 바꿔줘야 할때가 많다
.then(res => res.json())
.then(res => {
if(res.success {
console.log('${res.user.name}' 님 환영합니다);
}
});
-> 리액트 사용시,
import React, { useEffect } from 'react';
function User(props)
useEffect(() => {
const { userId } = props;
fetch('https://api.google.com/user/${userId}')
.then(res => res.json())
.then(res => {
if (res.success) {
console.log('${res.user.name}' 님 환영합니다)';
}
});
}, []);
...
}
3. fetch()함수 -method가 post인 경우
method가 post인 경우를 보겠다. fetch() 기본은 get이기 때문에 아무것도 작성하지 않아도 get으로 호출가능, but, post인 경우에는 fetch()함수에 method 정보를 인자로 넘겨 줘야 한다.
-> api 명세
설명: 유저를 저장한다.
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("저장 완료");
}
})
- 두 번째 인자에 method 와 body를 보내주어야 한다.
- method는 post
- body는 JSON형태로 보내기 위해 JSON.stringfy()함수에 객체를 인자로 전달하여 JSON형태로 변환.