Getting started with json-server

Goal

Set up json-server and axios

Agenda

  • Step 1: Set up package.json and install node modules
  • Step 2: Create index.html
  • Step 3: Create script.json
  • Step 4: Create db.json
  • Step 5: Run and results

Step 1: Set up package.json and install node modules

1
2
3
npm init -y
yarn add axios
yarn add concurrently json-server parcel-bundler --dev

Edit scripts in package.json

1
2
3
4
5
6
7
// package.json

"scripts": {
"client": "parcel index.html --open",
"server": "json-server --watch db.json",
"start": "concurrently \"yarn server\" \"yarn client\""
},

Step 2: Create index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>json-server demo</title>
<style>
* {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
</style>
</head>
<body>
<h2>json-server demo</h2>
<div>
<div><button id="getAllUsers">getAllUsers</button></div>

<div>
<input type="text" id="name" placeholder="name" />
<button id="addUser">addUser</button>
</div>

<div>
<input type="text" id="deleteUserId" placeholder="deleteUserId" />
<button id="deleteUser">deleteUser</button>
</div>
</div>
<p id="result"></p>

<script src="./script.js"></script>
</body>
</html>

Step 3: Create script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// script.js

import axios from 'axios';

const url = 'http://localhost:3000/users/';

const btn_getAllUsers = document.querySelector('#getAllUsers');
const btn_addUser = document.querySelector('#addUser');
const btn_deleteUser = document.querySelector('#deleteUser');
const result = document.querySelector('#result');

const log = data => {
console.log(data);
result.innerHTML = JSON.stringify(data);
};

const getAllUser = () => {
axios.get(url).then(res => log(res.data));
};

btn_getAllUsers.onclick = () => getAllUser();

btn_addUser.onclick = () => {
const newUser = {
id: new Date().valueOf(),
name: document.querySelector('#name').value
};

axios.post(url, newUser).then(res => {
log(res);
getAllUser();
});
};

btn_deleteUser.onclick = () => {
const deleteUserId = document.querySelector('#deleteUserId').value;
axios.delete(url + deleteUserId).then(res => getAllUser());
};

getAllUser();

Step 4: Create db.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// db.json

{
"users": [
{
"id": 1,
"name": "hoe"
},
{
"id": 2,
"name": "fua"
}
]
}

Step 5: Run and result

1
yarn start

json-server1

json-server2

json-server3