본문 바로가기

Front End/Javascript

[JavaScript] JSON-SERVER 사용해 보기

json-server란?

JSON Server는 JSON 파일을 이용해 모의용 RESTful API 서버 및 DB를 구축할 수 있는 도구입니다.
백엔드 API 서버나 DB가 준비되지 않은 상황에서도 프로토타입을 개발하거나 테스트때 사용하면 유용합니다.

 

https://www.npmjs.com/package/json-server

 

json-server

[![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg)](https://github.com/typicode/json-server/actions/workflows/node.js.yml). Latest version: 1.0.0-beta.3, last published: 21 days ago. Start using json-server in y

www.npmjs.com

 

json-server 설치 하기

c:\>md myJSONServer
c:\>cd  myJSONServer
c:\ myJSONServer>npm init -y
Wrote to c:\ myJSONServer\package.json:
{
  "name": "jsonserver",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

c:\ myJSONServer>npm install json-server

added 45 packages, and audited 46 packages in 9s

14 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

 

다음과 같이 db.json 파일을 만든다.

{
    "member": [
        {
            "id": 1,
            "userName": "한사람",
            "phoneNumber": "010-1234-5678",
            "position": "BackEnd 개발자"
        },
        {
            "id": 2,
            "userName": "두인간",
            "phoneNumber": "010-4567-9874",
            "position": "FrontEnd 개발자"
        }
    ],
    "posts": [
        {
            "id": 1,
            "title": "첫번째 글입니다.",
            "author": "한사람"
        }
    ],
    "comments": [
        {
            "comment": "와 일빠다."
        },
        {
            "comment": "와 이빠다."
        }
    ],
    "todos" : [
        {
            "id":1,
            "todo" : "HTML 배우기"
        },
        {
            "id":2,
            "todo" : "CSS 배우기"
        },
        {
            "id":3,
            "todo" : "JavaScript 배우기"
        },
        {
            "id":4,
            "todo" : "JSON-Server 배우기"
        }
    ]
}

 

JSON파일의 형식은 다음과 같습니다. 컬렉션은 1개 이상 가질 수 있습니다.

{
     "컬렉션" : [
         {"필드":값, "필드":값, "필드":값 ....},
         {"필드":값, "필드":값, "필드":값 ....},
         {"필드":값, "필드":값, "필드":값 ....},
         ........
     ],
     "컬렉션" : [],     
     "컬렉션" : []
}

 

json-server 실행 하기

실행 명령
npx json-server [--watch] json파일이름 [--port 포트번호]

 

json파일의 이름과 서버의 포트 번호를 변경해서 실행이 가능합니다.

 

c:\ myJSONServer> npx json-server db.json
JSON Server started on PORT :3000
Press CTRL-C to stop
Watching db.json...

♡⸜(˶˃ ᵕ ˂˶)⸝♡

Index:
http://localhost:3000/

Static files:
Serving ./public directory if it exists

Endpoints:
http://localhost:3000/member
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/todos

 

http://localhost:3000/ 에 접속하면 다음과 같은 화면을 만날 수 있습니다.

 

다음과 같은 Endpoint가 생성이 됩니다.

 

객체에 id필드가 존재하는 경우 다음의 Endpoint가 생성이 됩니다.

GET           /posts
GET           /posts/:id
POST        /posts
PUT           /posts/:id
PATCH      /posts/:id
DELETE   /posts/:id

 

객체에 id필드가 존재하지 않는 경우 다음의 Endpoint가 생성이 됩니다.

GET       /comments
PUT       /comments
PATCH  /comments

 

HTTP Method는 크게 GET, POST, PUT, DELETE가 대표적입니다.
보통 CRUD에서 다음과 같이 이용합니다.

GET           값 요청
POST        저장
PUT           전체 수정
PATCH      일부 수정
DELETE   삭제

 

 

Params

Conditions

  • → ==
  • lt → <
  • lte → <=
  • gt → >
  • gte → >=
  • ne → !=
GET /posts?views_gt=9000

Range

  • start
  • end
  • limit
GET /posts?_start=10&_end=20
GET /posts?_start=10&_limit=10

Paginate

  • page
  • per_page (default = 10)
GET /posts?_page=1&_per_page=25

Sort

  • _sort=f1,f2
GET /posts?_sort=id,-views

Nested and array fields

  • x.y.z...
  • x.y.z[i]...
GET /foo?a.b=bar
GET /foo?x.y_lt=100
GET /foo?arr[0]=bar

Embed

GET /posts?_embed=comments
GET /comments?_embed=post

Delete

DELETE /posts/1
DELETE /posts/1?_dependent=comments

Serving static files

If you create a ./public directory, JSON Server will serve its content in addition to the REST API.

You can also add custom directories using -s/--static option.

json-server -s ./static
json-server -s ./static -s ./node_modules