프론트엔드 개발자를 위한 가상 서버 json-server 사용하기

HeeGeun.Lee·2022년 11월 13일
1

Introduction

프론트엔드 개발자가 원하는 타이밍에 맞춰서 백엔드 API가 개발되지 않는다면, 프론트엔드 개발자는 백엔드 API가 개발되어서 나올 때까지 기다릴 수 밖에 없게 되어 누수가 발생한다.
또 백엔드 개발자 입장에서는 API를 만들어 놨는데, 이게 동작하는지 프론트엔드 개발자가 테스트를 해줘야 하는데 아직 개발이 안 되었다면, 그 또한 누수가 발생한다.
프론트엔드 개발자의 입장에서 이런 일이 발생하지 않게 하려고 사용하는 것이 바로 'json-server'이다.


1.서버 준비

1-1. 설치

npm install -g json-server

1-2. db.json 만들기

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" },
    { "id": 2, "title": "javascript", "author": "ecma" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

1-3. 서버 시작

json-server --watch db.json

1-4. 확인

💡 json-server


2. 서버 연결 (fetch API)

2-1. GET

 function getData() {
   fetch('http://localhost:3000/posts')
     .then((response) => {
     return response.json(); // Promise 객체 리턴
   })
     .then((json) => {
     console.log(json);
     // 	[{id: 1, title: 'json-server', author: 'typicode'},
     // 	{id: 2, title: 'javascript', author: 'ecma'}]
   });
 }
getData();

2-2. POST

const headers = { 'content-type': 'application/json;charset=UTF-8' };

function postData() {
  const data = { title: 'html', author: 'Jeremy' };

  fetch('http://localhost:3000/posts', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: headers,
  })
    .then((response) => response.json())
    .then((json) => console.log(json)); // {title: 'html', author: 'Jeremy', id: 3}
}

2-3. PUT

const headers = { 'content-type': 'application/json;charset=UTF-8' };

function putData() {
  const data = { title: 'css', author: 'Jeremy' };
  
  fetch('http://localhost:3000/posts/3', {
    method: 'PUT',
    body: JSON.stringify(data),
    headers: headers,
  })
    .then((response) => response.json())
    .then((json) => console.log(json)); // {title: 'css', author: 'Jeremy', id: 3}
}

2-4. DELETE

function deleteData() {
  fetch('http://localhost:3000/posts/3', {
    method: 'DELETE',
  })
    .then((response) => response.json())
    .then((json) => console.log(json)); // {}
}

결론

가상서버 json-server와 fetch API를 이용하여 데이터를 response, request를 주고받아 봤다.
json-server는 실제 백엔드 API와 99% 같게 동작한다고 하니 실무에서 유용하게 쓸 수 있겠다.

profile
느리지만 천천히.

0개의 댓글