React

json-server ๊ตฌ์ถ•ํ•ด์„œ React ํ”„๋กœ์ ํŠธ

martinooo 2022. 12. 19. 14:21

git address: https://github.com/yoogukhyeon/react-study-group/tree/api


๐Ÿคท‍โ™‚๏ธ json-server๋ž€?


ํ”„๋ก ํŠธ์—”ํŠธ ์‚ฌ์ด๋“œํ”„๋กœ์ ํŠธ ํ˜น์€ ๊ฐœ๋ฐœ์„ ํ•˜๋‹ค๋ณด๋ฉด server ๋ฐ์ดํ„ฐ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. 

๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์— ๋งŽ์€ ์‹œ๊ฐ„์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค๋ฉด json-server๋ฅผ ํ™œ์šฉํ•ด์„œ API์„œ๋ฒ„๋ฅผ ๋งŒ๋“ค์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

์ด๋Ÿฐ ๊ฒฝ์šฐ์— ํ•„์š”ํ•œ ๋„๊ตฌ๊ฐ€ json-server ์ž…๋‹ˆ๋‹ค.

 ์ฐธ๊ณ ๋กœ ์ด ๋„๊ตฌ๋Š” ํ”„๋กœ๋•์…˜์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ์œ„ํ•˜์—ฌ ๋งŒ๋“ค์–ด์ง„๊ฒƒ์ž…๋‹ˆ๋‹ค. ์‹ค์ œ ์šด์˜์—์„œ๋Š” ์‚ฌ์šฉํ•˜์‹œ๋ฉด ์•ˆ๋ฉ๋‹ˆ๋‹ค.
* ํ”„๋ก ํŠธ์—”๋“œ ํ…Œ์ŠคํŠธ ์šฉ๋„ 

 

1. json-server npm ์„ค์น˜ 

npm i -D json-server //dev์— ์„ค์น˜

ํ”„๋กœ์ ํŠธ package.json์— scripts ์ถ”๊ฐ€ 

    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "json-server": "json-server db.json --port 8080",
        "start:dev": "concurrently \"npm run start\" \"npm run json-server\"",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },

 

2. json-server ์„œ๋ฒ„ ๋„์šฐ๊ธฐ

 

npm run json-server ๋ช…๋ น์–ด ์ž…๋ ฅ

 

3. ํ”„๋กœ์ ํŠธ ์ตœ์ƒ์œ„์— db.json ํŒŒ์ผ์„ ๋งŒ๋“ญ๋‹ˆ๋‹ค. (๊ฐ„๋‹จํ•˜๊ฒŒ ๋งŒ๋“ค์–ด ๋ดค์Šต๋‹ˆ๋‹ค.)

{
  "boards": [
    {
      "id": 1,
      "nickName": "ํ”ผ์นด์ถ”",
      "title": "ํ›„๊ธฐ ๋‚จ๊ฒจ์š” ํ”ผ์นด์ธ„!",
      "views": 21,
      "likes": 24,
      "diffDate": "1๋ถ„์ „",
      "commentCount": 3
    },
    {
      "id": 2,
      "nickName": "๋ผ์ด์ธ„",
      "title": "ํ›„๊ธฐ ๋‚จ๊ฒจ์š” ๋ผ์ด์ธ„!",
      "views": 2,
      "likes": 31,
      "diffDate": "30๋ถ„์ „",
      "commentCount": 27
    },
    {
      "id": 3,
      "nickName": "๊ผฌ๋ถ์ด",
      "title": "ํ›„๊ธฐ ๋‚จ๊ฒจ์š”! ๊ผฌ๋ถ์ด",
      "views": 30,
      "likes": 2,
      "diffDate": "1๋ถ„์ „",
      "commentCount": 3
    },
    {
      "id": 4,
      "nickName": "ํŒŒ์ด๋ฆฌ",
      "title": "ํ›„๊ธฐ ๋‚จ๊ฒจ์š”! ํŒŒ์ด๋ฆฌ",
      "views": 50,
      "likes": 100,
      "diffDate": "1์‹œ๊ฐ„์ „",
      "commentCount": 3
    },
    {
      "id": 5,
      "nickName": "์ด์ƒํ•ด์”จ",
      "title": "ํ›„๊ธฐ ๋‚จ๊ฒจ์š”! ์ด์ƒํ•ด์”จ",
      "views": 0,
      "likes": 0,
      "diffDate": "1๋ถ„์ „",
      "commentCount": 0
    },
    {
      "id": 6,
      "nickName": "๋งŒ๋‚˜๋‡ฝ",
      "title": "ํ›„๊ธฐ ๋‚จ๊ฒจ์š”! ๋งŒ๋‚˜๋‡ฝ",
      "views": 2,
      "likes": 20,
      "diffDate": "3๋ถ„์ „",
      "commentCount": 3
    }
  ]
}

 

4. Postman ํ™œ์šฉํ•ด์„œ API ์„œ๋ฒ„ ํ…Œ์ŠคํŠธ (db.json์— ๋ฐ์ดํ„ฐ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.)

 

* POST, GET, PUT, DELETE ํ™œ์šฉํ•ด์„œ CRUD ํ…Œ์ŠคํŠธ๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค!