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

Harimad·2022년 8월 11일
1

js

목록 보기
5/14
post-thumbnail

0. 들어가며

json-server는 json 파일을 사용해서 간단한 시뮬레이션을 위한 REST API Mock server를 구축할 수 있는 툴 입니다. - PoiemaWeb

  • json-server는 30초 안에 REST API를 구축해주는 라이브러리 입니다. 하지만 이는 실제 프로덕션에서는 사용하지 않습니다.
  • json-server는 번거로운 백엔드 api를 만들어서 사용하는 것 대신에, 간편하게 서버로 api 테스트를 해보고 싶을 때 사용하기 좋습니다.

1. 시작


1-1. json-server 설치

npm install -g json-server

1-2. db.json 파일 생성

프로젝트 루프 폴더에 db.json 파일을 생성합니다.
그리고 아래의 데이터를 저장해 줍다.

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

1-3. json-server 실행

터미널에서 아래의 코드를 입력해여 JSON server를 실행합니다.

json-server --watch db.json

실행결과

$ json-server --watch db.json

  \{^_^}/ hi!

  Loading db.json
  Oops, db.json doesn't seem to exist
  Creating db.json with some default data

  Done

  Resources
  http://localhost:3000/posts
  http://localhost:3000/comments
  http://localhost:3000/profile

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

이제 Resources에 있는 url중에
http://localhost:3000/posts 을 방문하면 db.json에 넣은 데이터중에 key가 posts인 value 값을 얻을 수 있습니다.

[
	{
  		id: 1,
  		title: "json-server",
  		author: "typicode"
    }
]

2. HTTP


2-1. HTTP 통신 이란?

HTTP(HyperText Transfer Protocol)는 W3 상에서 정보를 주고받을 수 있는 프로토콜이다. - 위키백과

대표적인 HTTP Method는 아래와 같습니다.

  • GET - 리소스 요청
  • POST - 리소스 생성
  • PUT - 리소스 수정
  • DELETE - 리소스 삭제

3. XMLHttpRequest

  • 여기서 알아야할 용어중 하나는 ajax입니다.
  • ajax는 Asynchronous JavaScript and XML의 약자 입니다.
  • ajax는 웹 페이지 전체를 다시 로딩하지 않고, 일부분만 갱신할 수 있습니다.
  • 이때 서버와 JSON, XML, HTML, txt파일 등등의 데이터를 주고받을 수 있습니다.
  • 브라우저에서 XMLHttpRequest라는 API로 ajax를 사용할 수 있습니다.
  • XMLHttpRequest는 브라우저와 웹 서버 간에 통신을 해서 데이터를 가져올 수 있는 API입니다.
  • XMLHttpRequest는 옵션을 통해서 비동기/동기 방식 모두를 사용할 수 있습니다.
  • XMLHttpRequest로 ajax 방식의 통신을 하기위해서 먼저 인스턴스를 생성하고 open() 메서드로 통신 요청 환경을 만들어야 합니다.
const xhr = new XMLHttpRequest();
const method = 'POST'; //'GET', 'PUT', 'DELETE' 메서드가 가능
const url = '원하는 url';
xhr.open(method, url); // 문법: open(HTTP Method, Url)
  • 요청에 헤더를 지정하려면 setRequestHeader() 메서드를 사용합니다.
xhr.setRequestHeader('content-type', 'application/json');

-서버로 부터 응답을 받으면 onload() 메서드로 응답 받은 데이터를 사용합니다.

xhr.onload = () => {
  	//...
}

3-1. GET - 데이터 얻기

function getPostData() {
  const xhr = new XMLHttpRequest(); // XMLHttpRequest 객체 생성

  xhr.open("GET", "http://localhost:3000/posts");   
  xhr.setRequestHeader("content-type", "application/json");
  xhr.send();

  // 서버로 부터 응답 받으면 실행
  xhr.onload = () => {
    if (xhr.status === 200) {
      const res = JSON.parse(xhr.response);
      console.log(res);
    } else {
      console.log(xhr.status, xhr.statusText);
    }
  }
}

getPostData();

실행결과

[{…}]

0: {id: 1, title: 'json-server', author: 'typicode'}
length: 1
[[Prototype]]: Array(0)

3-2. POST - 데이터 전송

  • 생성 버튼을 누르면 data변수에 저장된 데이터가 db.json 파일의 key가 posts인 객체에 저장됩니다.
  • POST 방식은 content-type에 charset-UTF-8을 추가해 줘야합니다.
<body>
  <button onclick="postData()">생성</button>
  <script>
    function postData() {
    	const xhr = new XMLHttpRequest();
    	xhr.open("POST", "http://localhost:3000/posts");
    	xhr.setRequestHeader("content-type", "application/json; charset=UTF-8")
		//db.json 파일의 posts 객체에 있는 key가 id인 값은 유일한 값이라서 안넣어줘도 자동으로 생성됨.
    	const data = { title: 'JavaScript', author: 'John Doe' };
    	xhr.send(JSON.stringify(data));

    	xhr.onload = () => {
    		if (xhr.status === 201) {
    			const res = JSON.parse(xhr.response);
    			console.log(res);
    		} else {
    			console.log(xhr.status, xhr.statusText);
    		}
    	}
    }
  </script>
</body>
  • 데이터조회
    위에서 만든 getPostData() 함수를 다시 호출하면 데이터가 잘 저장된 것을 볼 수 있습니다.
getPostData();

/* 실행결과
** (2) [{…}, {…}]
** 0: {id: 1, title: 'json-server', author: 'typicode'}
** 1: {title: 'JavaScript', author: 'John Doe', id: 2}
** length: 2
** [[Prototype]]: Array(0)
*/

3-3. PUT - 데이터 수정

  • 수정 버튼을 누르면 posts 데이터의 url뒤에 붙은 id값이 2인 값이 data 변수에 설정한 대로 수정됩니다.
<body>
  <button onclick="putData()">수정</button>
  <script>
    function putData() {
    	const xhr = new XMLHttpRequest();
    	xhr.open("PUT", "http://localhost:3000/posts/2");
    	xhr.setRequestHeader("content-type", "application/json; charset=UTF-8");
    	const data = { title: "HTML", author: "Heung Min SON" };
    	xhr.send(JSON.stringify(data));

    	xhr.onload = () => {
          if (xhr.status === 200) {
              const res = JSON.parse(xhr.response);
              console.log(res);
          } else {
              console.log(xhr.status, xhr.statusText);
          }
      	}
      }
   </script>
</body>
  • 데이터조회
    수정 버튼을 누른 후 값이 바뀐걸 알 수 있습니다.
    posts의 id가 2인 녀석의 title이 HTML로 변경되었습니다.
getPostData();

/* 실행결과
** (2) [{…}, {…}]
** 0: {id: 1, title: 'json-server', author: 'typicode'}
** 1: {title: 'HTML', author: 'John Doe', id: 2}
** length: 2
** [[Prototype]]: Array(0)
*/

3-4. DELETE - 데이터 삭제

  • 데이터 삭제는 수정과 비슷합니다.
  • 삭제 버튼을 누르면 posts의 id가 2번인 녀석이 삭제됩니다.
<body>
  <button onclick="deleteData()">삭제</button>
  <script>
    function deleteData() {
    	const xhr = new XMLHttpRequest();

    	xhr.open("DELETE", "http://localhost:3000/posts/2");
    	xhr.getResponseHeader("content-type", "application/json; charset=UTF-8")
    	xhr.send();

    	xhr.onload = () => {
    		if (xhr.status === 200) {
              const res = JSON.parse(xhr.response);
              console.log(res);
        	} else {
    		  console.log(xhr.status, xhr.statusText);
       		}
        }
    }
   </script>
</body>
  • 데이터조회
    posts의 데이터를 다시 조회해 봅니다. id가 2인 값이 삭제되었습니다.
getPostData();

/* 실행결과
** (1) [{…}]
** 0: {id: 1, title: 'json-server', author: 'typicode'}
** length: 1
** [[Prototype]]: Array(0)
*/

4. 마무리하며

  • 지금까지 간단하게 가상의 서버 json-server를 설치하고 데이터를 조작해 봤습니다.
  • json-server 를 실행하면서 서버에 데이터를 조작하는데 XMLHttpRequest 객체를 사용해 봤습니다.
  • XMLHttpRequest 대신 fetch() 메서드나 async & await 을 사용할 수도 있습니다.
  • json-server 를 사용해 보면서 간편하게 REST API를 적용해 볼 수 있다는 점이 매력적인것 같습니다.

참고

profile
Here and Now. 🧗‍♂️

0개의 댓글