[환경]
Clinet: React
Server: json-server
1. JSON server
json 파일을 사용해서 가짜 REST API 서버를 생성할 수 있는 도구이다.
이것은 실제 서버가 아닌 개발용 서버로 사용하는 것이 좋으며, 만약 실제 프로젝트를
개발하기 위해서는 실제 백엔드 서버를 구축해야한다.
2. JSON server 설치하기
npm 또는 yarn을 사용해서 전역으로 설치해준다.
** npm
$ npm i -g json-server
** yarn
$ yarn global add json-server
|
3. Dummy Data 만들기
가짜 서버를 만들기 위해서는 json 형식의 데이터가 필요하다.
먼저 dummy.json 이란 파일을 만들어보자!
data/dummy.json
{
"todos": [
{
"id": 1,
"content": "산책하기",
"completed": true
},
{
"id": 2,
"content": "프로그래밍 공부하기",
"completed": false
},
{
"id": 3,
"content": "영어 공부하기",
"completed": true
}
]
}
|
3. json-server 로 가짜 서버 실행하기
dummy.json 을 작성했으면 이젠 json-server로 실행해보자!
json-server --watch dummy.json --port 8083
|
◎ --watch 옵션은 생략 가능하다.
◎ --port 다음에는 port 번호를 적어준다.
(포트 번호는 맘대로 해도 상관은 없다. 되도록 사용하지 않는 포트 번호로 사용하기)
4. 결과 확인하기
json-server를 실행하면 아래와 같은 결과가 뜬다.
\{^_^}/ hi!
Loading dummy.json
Done
Resources
http://localhost:8083/todos
Home
http://localhost:8083
|
5. 가짜 API 서버 (port: 8083) 열기
아래 url에 들어가서 확인해보기
http://localhost:8083/todos
|
http://localhost:8083/todos
6. axios를 사용해서 api 요청해보기
서버 생성은 완료했다. 이젠 Client 측에서 요청을 해보도록 하자!
일단, Client의 REST API 요청을 하기 위해서 (ajax 작업) axios를 설치한다.
(물론 Postman을 사용해도 좋다)
** npm
$ npm i axios
** yarn
$ yarn add axios
|
axios 를 설치했으면 다음으로 실제 API 요청을 하도록 로직을 작성한다.
(api 폴더를 만들기 todos api를 작성한다.)
api/todos.js
import axios from 'axios';
const BASE_URL = 'http://localhost:8083';
export const getTodos = async () => {
try {
const res = await axios.get(`${BASE_URL}/todos`);
return res.data;
} catch (error) {
return error.message;
}
};
|
app.js
import React, { useState, useEffect } from 'react';
import { getTodos } from './api/todos';
import './app.css';
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
(async () => {
try {
const result = await getTodos();
setTodos(result);
} catch (e) {
console.error(e.message);
}
})();
}, []);
return (
<div className="App">
<ul>
{todos &&
todos.map((todo, idx) => (
<li
key={todo.id}
style={
todo.completed
? { textDecoration: 'line-through', opacity: 0.8 }
: { color: '#000', fontWeight: 'bolder' }
}
>
{todo.content}
</li>
))}
</ul>
</div>
);
}
export default App;
|
[결과화면]
끝!
'Frontend study > 정리 및 기록' 카테고리의 다른 글
React@18과 react-router-dom@5의 호환성 문제 (0) | 2022.07.15 |
---|---|
CRA에서 절대경로 설정하기 (0) | 2022.07.02 |
React Proxy 설정하기 (0) | 2022.06.22 |
HTTP 프로토콜 (0) | 2022.02.27 |
npx create-react-app 설치 에러 (0) | 2022.01.01 |