json-server 사용해보기
json-server는 fake server의 대표적인 예시로, 간단한 DB와 API 서버를 생성해주는 패키지이다. BE에서 먼저 API server 가 구축되어야 FE에서 실제 데이터로 작업할 수 있기 때문에 만약 그 시간을 기다린다면 낭비가 될 것이다. 그래서 mock data를 이 json-server를 통해 생성하고 미리 작업하고 있을 수 있다. (배포까지 가능)
npm install -g json-server
패키지 설치하고 최상위 폴더에 db.json 파일을 생성하고 아래의 json 방식의 코드를 입력한다.
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
특정 서버 포트를 따로 지정해주는 것이 좋다. 실제로 서버가 돌아가는 것 처럼 ....
리액트 앱 FE와 포트가 겹치지 않게 4000으로 지정하는 것이 일반적이다.
json-server --watch db.json --port 4000
Resources를 확인해보면 아까 db에 입력했던 mock data가 생성된다. db.json에 데이터를 더 넣어서 확인해보자
http://localhost:4000/comments
HTTP 요청을 할 때는 아래를 참고!
이 path 와 query를 적절히 섞어서 사용하면 된다.
const fetchTodos = async () => {
const { data } = await axios.get("http://localhost:4000/todos");
console.log("data", data);
setTodos(data);
};
https://www.npmjs.com/package/json-server
json-server
Get a full fake REST API with zero coding in less than 30 seconds. Latest version: 0.17.3, last published: 3 months ago. Start using json-server in your project by running `npm i json-server`. There are 315 other projects in the npm registry using json-ser
www.npmjs.com