백앤드로부터 데이터를 받아오려면 api를 호출하고 데이터를 응답받습니다. 이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios 라이브러리를 사용할 수 있습니다.
참고로 Web API는 클라이언트 측에서 사용할 수 있는 자바스크립트 내장함수라고 생각하시면 됩니다.
fetch('api 주소')
.then(res => res.json())
.then(res => {
// data를 응답 받은 후의 로직
});
fetch('api 주소')
.then(function(res) {
return res.json();
})
.then(function(res) {
// data를 응답 받은 후의 로직
});
설명: 유저 정보를 가져온다.
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}` 님 환영합니다);
}
});
}
}