Build a blog with a JSON server



A fast improvement demo utilizing JSON server

This tutorial is supposed for these with some data of Javascript and html.
The aim of constructing this weblog is to jot down down the detailed operation historical past and my memo for studying the Js.
In case you are additionally and wish to get arms soiled, simply observe these steps under and have enjoyable!~



Conditions

  • VS code with Dwell Server (Utilizing VScode Extensions)
  • node.js



Getting Began

Obtain the starter challenge for this demo: DemoBlog

Set up the JSON server globally:

npm set up -g json-server
Enter fullscreen mode

Exit fullscreen mode

Create a folder named knowledge within the starter challenge root listing and create a file named db.json contained in the folder.

Copy and paste the next content material into file 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
        }
    ]
}
Enter fullscreen mode

Exit fullscreen mode

Run the JSON server on the root listing of this challenge:

json-server --watch knowledge/db.json
Enter fullscreen mode

Exit fullscreen mode

This command will immediate json server to observe the json file db.json and provides us entry to API endpoints to work together with assets on this json file.

The output message is perhaps like the next:

  {^_^}/ hello!

  Loading knowledge/db.json
  Finished

  Assets
  http://localhost:3000/posts

  House
  http://localhost:3000

  Kind s + enter at any time to create a snapshot of the database
  Watching...
Enter fullscreen mode

Exit fullscreen mode

Now proper click on index.html within the challenge root listing and choose Open with Dwell Server, and we must always see the assets utilizing examine:

Replace the next content material to the js/create.js file:

// javascript for create.html
const kind = doc.querySelector('kind');
const createPost = async (e) => {
    e.preventDefault();
    const doc = {
        title: kind.title.worth,
        physique: kind.physique.worth,
        likes: 10
    }
    await fetch('http://localhost:3000/posts', {
        methodology: 'POST',
        physique: JSON.stringify(doc),
        headers: { 'Content material-Kind': 'software/json' }
    });
    window.location.exchange('/index.html');
}
kind.addEventListener('submit', createPost);
Enter fullscreen mode

Exit fullscreen mode

Replace the next content material to the js/element.js file:

// javascript for particulars.html
const id = new URLSearchParams(window.location.search).get('id');
const container = doc.querySelector('.particulars');
const deleteBtn = doc.querySelector('.delete');

const renderDetails = async () => {
    const res = await fetch(`http://localhost:3000/posts/${id}`);
    const publish = await res.json();

    const template = `
        <h1>${publish.title}</h1>
        <p>${publish.physique}</p>
        `
    container.innerHTML = template;
}
deleteBtn.addEventListener('click on', async (e) => {
    e.preventDefault();
    await fetch(`http://localhost:3000/posts/${id}`, {
        methodology: 'DELETE'
    });
    window.location.exchange('/index.html');
})
window.addEventListener('DOMContentLoaded', () => renderDetails());
Enter fullscreen mode

Exit fullscreen mode

Replace the next content material to the js/index.js file:

// javascript for index.html
const container = doc.querySelector('.blogs');
const searchForm = doc.querySelector('.search');

const renderPosts = async (time period) => {
    let uri = 'http://localhost:3000/posts?_sort=likes&_order=desc';
    if (time period) {
        uri += `&q=${time period}`;
    }
    const res = await fetch(uri);
    const posts = await res.json();
    let template = '';
    posts.forEach(publish => {
        template += `
            <div class="publish">
                <h1>${publish.title}</h1>
                <p><small>${publish.likes} likes</small></p>
                <p>${publish.physique.slice(0, 200)}</p>
                <a href="https://style-tricks.com/particulars.html?id=${ publish.id }">Learn extra...</a>
            </div>
        `
    })
    container.innerHTML = template;
}
searchForm.addEventListener('submit', e => {
    e.preventDefault();
    renderPosts(searchForm.time period.worth.trim())
})
window.addEventListener('DOMContentLoaded', () => renderPosts());
Enter fullscreen mode

Exit fullscreen mode

Replace the next content material to the create.html file:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta title="viewport" content material="width=device-width, initial-scale=1.0">
  <hyperlink rel="stylesheet" href="types.css">
  <title>JSON Server</title>
</head>
<physique>
  <h1>Create a New Weblog</h1>
  <kind>
    <enter kind="textual content" title="title" required placeholder="Weblog title">
    <textarea title="physique" required placeholder="Weblog physique"></textarea>
    <button>Create</button>
  </kind>
  <script src="js/create.js"></script>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Replace the next content material to the element.html file:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta title="viewport" content material="width=device-width, initial-scale=1.0">
  <hyperlink rel="stylesheet" href="types.css">
  <title>JSON Server</title>
</head>
<physique>
  <div class="particulars">
    <!-- inject weblog particulars right here -->
  </div>
  <button class="delete">Delete</button>
  <script src="js/particulars.js"></script>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Replace the next content material to the index.html file:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta title="viewport" content material="width=device-width, initial-scale=1.0">
  <hyperlink rel="stylesheet" href="types.css">
  <title>JSON Server</title>
</head>
<physique>
  <nav>
    <h1>All Blogs</h1>
    <a href="/create.html">Add a brand new weblog</a>
  </nav>
  <kind class="search">
    <enter kind="textual content" title="time period" placeholder="search time period">
    <button kind="submit">Search</button>
  </kind>
  <div class="blogs">
    <!-- inject blogs right here from js -->
  </div>
  <script src="js/index.js"></script>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Replace the next content material to the types.css file:

@import url('https://fonts.googleapis.com/css2?household=Roboto:wght@300;400;500;700&show=swap');

/* base types */
physique {
  background: #eee;
  font-family: 'Roboto';
  shade: #444;
  max-width: 960px;
  margin: 100px auto;
  padding: 10px;
}
nav {
  show: flex;
  justify-content: space-between;
}
nav h1 {
  margin: 0;
}
nav a {
  shade: white;
  text-decoration: none;
  background: #36cca2;
  padding: 10px;
  border-radius: 10px;
}
kind {
  max-width: 500px;
}
kind enter {
  width: 100%;
}
enter, textarea {
  show: block;
  margin: 16px 0;
  padding: 6px 10px;
  width: 100%;
  border: 1px stable #ddd;
  font-family: 'Roboto';
}
textarea {
  min-height:200px;
}
/* publish listing */
.publish {
  padding: 16px;
  background: white;
  border-radius: 10px;
  margin: 20px 0;
}
.publish h2 {
  margin: 0;
}
.publish p {
  margin-top: 0;
}
.publish a {
  shade: #36cca2;
}
Enter fullscreen mode

Exit fullscreen mode

Now we are able to work together with the JSON server utilizing this challenge:
Proper click on index.html within the challenge root listing and choose Open with Dwell Server, and we must always now see the next:

Image description

Image description



Reference

https://www.youtube.com/watch?v=VF3TI4Pj_kM&list=PL4cUxeGkcC9i2v2ZqJgydXIcRq_ZizIdD&index=2
https://www.npmjs.com/package/json-server



Closing Instance Code

DemoBlog

Add a Comment

Your email address will not be published. Required fields are marked *