JSON 서버로 블로그 구축
JSON 서버를 사용한 빠른 개발 데모
This tutorial is meant for those with some knowledge of Javascript and html.
The purpose of building this blog is to write down the detailed operation history and my memo for learning the Js.
If you are also interested and want to get hands dirty, just follow these steps below and have fun!~
전제 조건
시작하기
이 데모의 시작 프로젝트를 다운로드하십시오: DemoBlog
전역적으로 JSON 서버를 설치합니다.
npm install -g json-server
시작 프로젝트 루트 디렉터리에 data라는 폴더를 만들고 폴더 안에 db.json이라는 파일을 만듭니다.
다음 콘텐츠를 복사하여 db.json 파일에 붙여넣습니다.
{
"posts":[
{
"id":1,
"title":"Welcome to the new blog",
"body":"Book description: In June, 1954, eighteen-year-old Emmett Watson is driven home to Nebraska by the warden of the juvenile work farm where he has just served fifteen months for involuntary manslaughter. His mother long gone, his father recently deceased, and the family farm foreclosed upon by the bank, Emmett's intention is to pick up his eight-year-old brother, Billy, and head to California where they can start their lives anew. But when the warden drives away, Emmett discovers that two friends from the work farm have hidden themselves in the trunk of the warden's car. Together, they have hatched an altogether different plan for Emmett's future, one that will take them all on a fateful journey in the opposite direction—to the City of New York.",
"likes":30
},
{
"id":2,
"title":"How to be a good programmer",
"body":"Book description: In June, 1954, eighteen-year-old Emmett Watson is driven home to Nebraska by the warden of the juvenile work farm where he has just served fifteen months for involuntary manslaughter. His mother long gone, his father recently deceased, and the family farm foreclosed upon by the bank, Emmett's intention is to pick up his eight-year-old brother, Billy, and head to California where they can start their lives anew. But when the warden drives away, Emmett discovers that two friends from the work farm have hidden themselves in the trunk of the warden's car. Together, they have hatched an altogether different plan for Emmett's future, one that will take them all on a fateful journey in the opposite direction—to the City of New York.",
"likes":20
},
{
"id":3,
"title":"How to delete a post",
"body":"Book description: In June, 1954, eighteen-year-old Emmett Watson is driven home to Nebraska by the warden of the juvenile work farm where he has just served fifteen months for involuntary manslaughter. His mother long gone, his father recently deceased, and the family farm foreclosed upon by the bank, Emmett's intention is to pick up his eight-year-old brother, Billy, and head to California where they can start their lives anew. But when the warden drives away, Emmett discovers that two friends from the work farm have hidden themselves in the trunk of the warden's car. Together, they have hatched an altogether different plan for Emmett's future, one that will take them all on a fateful journey in the opposite direction—to the City of New York.",
"likes":31
},
{
"id":4,
"title":"This is the end of the world",
"body":"Book description: In June, 1954, eighteen-year-old Emmett Watson is driven home to Nebraska by the warden of the juvenile work farm where he has just served fifteen months for involuntary manslaughter. His mother long gone, his father recently deceased, and the family farm foreclosed upon by the bank, Emmett's intention is to pick up his eight-year-old brother, Billy, and head to California where they can start their lives anew. But when the warden drives away, Emmett discovers that two friends from the work farm have hidden themselves in the trunk of the warden's car. Together, they have hatched an altogether different plan for Emmett's future, one that will take them all on a fateful journey in the opposite direction—to the City of New York.",
"likes":15
}
]
}
이 프로젝트의 루트 디렉터리에서 JSON 서버를 실행합니다.
json-server --watch data/db.json
This command will prompt json server to watch the json file db.json and give us access to API endpoints to interact with resources in this json file.
출력 메시지는 다음과 같을 수 있습니다.
\{^_^}/ hi!
Loading data/db.json
Done
Resources
http://localhost:3000/posts
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
이제 프로젝트 루트 디렉터리에서 index.html을 마우스 오른쪽 버튼으로 클릭하고 Open with Live Server를 선택하면 inspect를 사용하여 리소스를 볼 수 있습니다.
다음 콘텐츠를 js/create.js 파일로 업데이트합니다.
// javascript for create.html
const form = document.querySelector('form');
const createPost = async (e) => {
e.preventDefault();
const doc = {
title: form.title.value,
body: form.body.value,
likes: 10
}
await fetch('http://localhost:3000/posts', {
method: 'POST',
body: JSON.stringify(doc),
headers: { 'Content-Type': 'application/json' }
});
window.location.replace('/index.html');
}
form.addEventListener('submit', createPost);
js/detail.js 파일에 다음 콘텐츠를 업데이트합니다.
// javascript for details.html
const id = new URLSearchParams(window.location.search).get('id');
const container = document.querySelector('.details');
const deleteBtn = document.querySelector('.delete');
const renderDetails = async () => {
const res = await fetch(`http://localhost:3000/posts/${id}`);
const post = await res.json();
const template = `
<h1>${post.title}</h1>
<p>${post.body}</p>
`
container.innerHTML = template;
}
deleteBtn.addEventListener('click', async (e) => {
e.preventDefault();
await fetch(`http://localhost:3000/posts/${id}`, {
method: 'DELETE'
});
window.location.replace('/index.html');
})
window.addEventListener('DOMContentLoaded', () => renderDetails());
js/index.js 파일에 다음 콘텐츠를 업데이트합니다.
// javascript for index.html
const container = document.querySelector('.blogs');
const searchForm = document.querySelector('.search');
const renderPosts = async (term) => {
let uri = 'http://localhost:3000/posts?_sort=likes&_order=desc';
if (term) {
uri += `&q=${term}`;
}
const res = await fetch(uri);
const posts = await res.json();
let template = '';
posts.forEach(post => {
template += `
<div class="post">
<h1>${post.title}</h1>
<p><small>${post.likes} likes</small></p>
<p>${post.body.slice(0, 200)}</p>
<a href="/details.html?id=${ post.id }">Read more...</a>
</div>
`
})
container.innerHTML = template;
}
searchForm.addEventListener('submit', e => {
e.preventDefault();
renderPosts(searchForm.term.value.trim())
})
window.addEventListener('DOMContentLoaded', () => renderPosts());
다음 콘텐츠를 create.html 파일로 업데이트합니다.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>JSON Server</title>
</head>
<body>
<h1>Create a New Blog</h1>
<form>
<input type="text" name="title" required placeholder="Blog title">
<textarea name="body" required placeholder="Blog body"></textarea>
<button>Create</button>
</form>
<script src="js/create.js"></script>
</body>
</html>
다음 콘텐츠를 detail.html 파일로 업데이트합니다.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>JSON Server</title>
</head>
<body>
<div class="details">
<!-- inject blog details here -->
</div>
<button class="delete">Delete</button>
<script src="js/details.js"></script>
</body>
</html>
다음 콘텐츠를 index.html 파일로 업데이트합니다.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>JSON Server</title>
</head>
<body>
<nav>
<h1>All Blogs</h1>
<a href="/create.html">Add a new blog</a>
</nav>
<form class="search">
<input type="text" name="term" placeholder="search term">
<button type="submit">Search</button>
</form>
<div class="blogs">
<!-- inject blogs here from js -->
</div>
<script src="js/index.js"></script>
</body>
</html>
다음 콘텐츠를 styles.css 파일로 업데이트합니다.
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
/* base styles */
body {
background: #eee;
font-family: 'Roboto';
color: #444;
max-width: 960px;
margin: 100px auto;
padding: 10px;
}
nav {
display: flex;
justify-content: space-between;
}
nav h1 {
margin: 0;
}
nav a {
color: white;
text-decoration: none;
background: #36cca2;
padding: 10px;
border-radius: 10px;
}
form {
max-width: 500px;
}
form input {
width: 100%;
}
input, textarea {
display: block;
margin: 16px 0;
padding: 6px 10px;
width: 100%;
border: 1px solid #ddd;
font-family: 'Roboto';
}
textarea {
min-height:200px;
}
/* post list */
.post {
padding: 16px;
background: white;
border-radius: 10px;
margin: 20px 0;
}
.post h2 {
margin: 0;
}
.post p {
margin-top: 0;
}
.post a {
color: #36cca2;
}
이제 이 프로젝트를 사용하여 JSON 서버와 상호 작용할 수 있습니다.
프로젝트 루트 디렉터리에서 index.html을 마우스 오른쪽 버튼으로 클릭하고 Open with Live Server를 선택하면 이제 다음이 표시됩니다.
참조
https://www.npmjs.com/package/json-server
최종 예제 코드
DemoBlog
Reference
이 문제에 관하여(JSON 서버로 블로그 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/yongchanghe/build-a-blog-with-a-json-server-2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)