ReactJS | Json-Server & Concurrently
json-server
가상의 데이터 서버를 구성할 수 있도록 도와주는 라이브러리
설치
yarn glodbal add json-server
데이터 입력
루트 폴더에 mock 폴더를 만들고 db.json이라는 파일을 만들어 가상의 데이터 입력
{
"data": [
{
"id": 1,
"name": "pathas",
"age": 1000,
},
{
"id": 2,
"name": "pathasHH",
"age": 1000,
}
]
}
json-server 구동
package.json에 json-server를 실행하는 "mockserver" 명령어 추가
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"mockserver": "json-server --watch --delay 500 --port 4000 mock/db.json"
}
...
yarn mockserver
성공 시 아래와 같은 화면 출력
$ json-server --watch --delay 500 --port 4000 mock/db.json
\{^_^}/ hi!
Loading mock/db.json
Done
Resources
http://localhost:4000/data
Home
http://localhost:4000
Type s + enter at any time to create a snapshot of the database
Watching...
GET /data 200 509.617 ms - 124
※ 터미널을 두 개 열어서 리액트 개발 서버와 json-server를 각각 구동해야 함
json-server 데이터 받기
http://localhost:4000/data 접속 시 다음과 같이 json 형식의 데이터 확인 가능
데이터를 실제로 받기 위해서는 XMLHttpRequest, fetch API, axios Library 등을 사용해야 함
concurrently
CRA는 기본적으로 개발 서버가 주어지기 때문에 json-server 또는 node.js로 구축한 서버를 동시에 실행시키려면
각각의 명령 프롬프트를 사용해야 하는데 concurrently 라이브러리를 사용하면 이를 한 번에 실행시킬 수 있음
설치
yarn add concurrently
사용
package.json에 concurrently를 사용한 명령어 추가
- 가장 앞에 concurrently 작성
- 각각의 명령어를 ""로 묶어 주어야하는데 ""안에 ""를 바로 사용할 수 없기 때문에 \ " \ " 사이에 명령어 작성
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"mockserver": "json-server --watch --delay 500 --port 4000 mock/db.json",
"dev": "concurrently \"yarn start\" \"yarn mockserver\"",
"eject": "react-scripts eject"
}
...
yarn dev
yarn dev만 입력해도 리액트 개발 서버와 json-server를 동시에 구동 가능
데이터 서버를 직접 구현하기 힘들거나 간단한 테스트가 필요할 때 사용할 수 있는 유용한 라이브러리인 json-server에 대해 살펴보았습니다. concurrently 라이브러리를 사용하면 json-server뿐만 아니라 실제 서버 역시 동시에 구동시킬 수 있게 됩니다.
실제 서버 구동 시에는 package.json 파일에 proxy 설정을 해주어야 하니 참고 바랍니다.
참고 도서: [ Do it! 리액트 프로그래밍 정석 / 저자: 박호준 / 출판사: 이지스퍼블리싱 ]