Back-End

[JSON-SERVER] json-server ์„ค์น˜ ๋ฐ ์‹คํ–‰ํ•˜๊ธฐ.

Bigone17 2023. 10. 11. 23:07

๐ŸŸก 1. json-server๋ž€?

  jsonํŒŒ์ผ์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ„๋‹จํ•œ ์‹œ๋ฎฌ๋ ˆ์ด์…˜์„ ์œ„ํ•œ REST API Mock server๋ฅผ ๊ตฌ์ถ•ํ•  ์ˆ˜ ์žˆ๋Š” ํˆด์ž…๋‹ˆ๋‹ค.

 

๐ŸŸก 2. json-server ์„ค์น˜ํ•˜๊ธฐ.

 ๐ŸŸฃ 2.1 module ์„ค์น˜ํ•˜๊ธฐ.

$ mkdir json-server-exam && cd json-server-exam
$ npm init -y
$ npm install json-server --save-dev

 

  ๐ŸŸฃ 2.2 mock.json ํŒŒ์ผ ์ƒ์„ฑํ•˜๊ธฐ.

   ์œ„์—์„œ ๋งŒ๋“  ํ”„๋กœ์ ํŠธ root ๊ฒฝ๋กœ(package.json๊ณผ ๋™์ผํ•œ ์œ„์น˜)์—  mock.json(์ด๋ฆ„์€ ์ž๊ธฐ์›ํ•˜๋Š” ๋Œ€๋กœ) ๋งŒ๋“ญ๋‹ˆ๋‹ค.

// mock.json
{
  "todos": [
    {
      "id": 1,
      "content": "HTML",
      "completed": true
    },
    {
      "id": 2,
      "content": "React",
      "completed": false
    },
    {
      "id": 3,
      "content": "JAVA",
      "completed": true
    }
  ],
  "users": [
    {
      "id": 1,
      "name": "Lee",
      "role": "developer"
    },
    {
      "id": 2,
      "name": "Kim",
      "role": "designer"
    }
  ]
}

 

 

๐ŸŸก 3. json-server ์‹คํ–‰ํ•˜๊ธฐ.

// package.json

...
"scripts": {
    "start": "json-server --watch mock.json -p 3009"
  },
  ...

  json-server๊ฐ€ ์‹คํ–‰ํ•˜๋ฉด, mock.jsonํŒŒ์ผ์„ ๋ฐ”๋ผ๋ณด๊ฒŒ ํ•˜๋ฉด์„œ, 3009๋ฒˆ ํฌํŠธ๋กœ ์‹คํ–‰ํ•˜๊ฒŒ ํ•˜๋Š” ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

3009๋ฒˆ ํฌํŠธ๋ฅผ ์ž„์˜๋กœ ์„ค์ •ํ•ด์ค€ ์ด์œ ๋Š”, ์ €๋Š” next.js(port:3000)์—์„œ json-server๋ฅผ ํ˜ธ์ถœํ•˜๊ธฐ ์œ„ํ•ด์„œ ์ž…๋‹ˆ๋‹ค.

 

// npm
npm run start


// yarn
yarn start

๋‘˜ ์ค‘ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฑธ๋กœ ์‹คํ–‰ํ•ด์ค๋‹ˆ๋‹ค.

 

 

๐ŸŸก 3. json-server ํ…Œ์ŠคํŠธํ•ด๋ณด๊ธฐ.

๐ŸŸฃ 3.1 postman์„ ์ด์šฉํ•˜์—ฌ ํ…Œ์ŠคํŠธํ•ด๋ณด๊ธฐ.

 

๐ŸŸฃ 3.2 next.js์—์„œ ํ˜ธ์ถœํ•˜๊ธฐ.

// server๋ฅผ ๋ถ€๋ฅด๊ณ  ์‹ถ์€ ํŒŒ์ผ
axios.defaults.baseURL = "http://localhost:3009";

  const getList = async() => {
    try{
      const response = await axios.get("/todos");
      console.log(response)
    }catch(e){
      console.log(e)
    }
  }

 

 

 

๐Ÿ“ ์ •๋ฆฌ 

  1. server ๊ตฌ์ถ• ์—†์ด client์—์„œ ๋น ๋ฅด๊ฒŒ api ํ…Œ์ŠคํŠธํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๋‹ค.
  2. ์ƒˆ๋กœ์šด ํด๋”์— npm install json-server --save-dev
  3. mock.json ํŒŒ์ผ ์ƒ์„ฑ
  4. package.json ํŒŒ์ผ์— "start": "json-server --watch mock.json -p 3009" ์ถ”๊ฐ€

 

 

๊ธด ๊ธ€ ์ฝ์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :) 
ํ‹€๋ฆฐ ๋‚ด์šฉ์ด ์žˆ๊ฑฐ๋‚˜, ๋ง๋ถ™์ผ ๋‚ด์šฉ์ด ์žˆ๋‹ค๋ฉด ์–ธ์ œ๋“ ์ง€ ๋Œ“๊ธ€ ๋‹ฌ์•„์ฃผ์„ธ์š”!
์ œ ๊ธ€์ด ์กฐ๊ธˆ์ด๋‚˜๋งˆ ์ฝ์œผ์‹  ๋ถ„๋“ค์—๊ฒŒ ๋„์›€์ด ๋˜๋„๋ก ๋…ธ๋ ฅํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค
๋‹ค์Œ ํŽธ์— ๋ดฌ์š”~

728x90
๋ฐ˜์‘ํ˜•

'Back-End' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[JSON-SERVER] mac์—์„œ json-server Forbidden error  (0) 2023.10.11