프론트엔드 개발자가 원하는 타이밍에 맞춰서 백엔드 API가 개발되지 않는다면, 프론트엔드 개발자는 백엔드 API가 개발되어서 나올 때까지 기다릴 수 밖에 없게 되어 누수가 발생한다.
또 백엔드 개발자 입장에서는 API를 만들어 놨는데, 이게 동작하는지 프론트엔드 개발자가 테스트를 해줘야 하는데 아직 개발이 안 되었다면, 그 또한 누수가 발생한다.
프론트엔드 개발자의 입장에서 이런 일이 발생하지 않게 하려고 사용하는 것이 바로 'json-server'이다.
npm install -g json-server
{
"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" }
}
json-server --watch db.json
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();
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}
}
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}
}
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% 같게 동작한다고 하니 실무에서 유용하게 쓸 수 있겠다.