Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Express Project to Build CRUD REST API From JSON Using JSON-Server Library in Browser

Posted on February 14, 2023

 

 

Welcome folks today in this blog post we will be building the crud rest api from json file using json-server library in browser using javascript. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

In order to get started you need to make a new node.js project using the below command as shown below

 

 

npm init -y

 

 

npm i express

 

 

npm i json-server

 

 

npm i ejs

 

 

And now you will see the below directory structure of the node.js app as shown below

 

 

 

 

 

 

Installing JSON-Server Globally

 

 

You can even install the json-server library globally inside the system by executing the below command

 

 

npm i -g json-server

 

 

And then we need to create the api.json file and copy paste the following json code

 

 

api.json

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "users": [
    {
      "name": "JOHN WILLAISMON LATHAM",
      "age": "24",
      "country": "Uganda"
    },
    {
      "name": "JOHN WILLAISMON LATHAM",
      "age": "27",
      "country": "India"
    },
    {
      "name": "JOHN WILLAISMON LATHAM",
      "age": "44",
      "country": "New Zealand"
    },
    {
      "name": "JOHN WILLAISMON LATHAM",
      "age": "34",
      "country": "Pakistan"
    }
  ]
}

 

 

And now we can start the api using the below command

 

 

json-server api.json

 

 

It will host the backend api at the port 3000

 

 

http://localhost:3000/users

 

 

 

 

 

Express App

 

 

Now we can turn this into an express app by making an index.js file and copy paste the following code

 

 

index.js

 

 

JavaScript
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
const express = require("express");
const jsonServer = require("json-server");
const fs = require("fs");
const bodyparser = require("body-parser");
 
const app = express();
 
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
 
const jsonServerMiddleware = jsonServer.router("api.json");
app.use("/api", jsonServerMiddleware);
 
app.set("view engine", "ejs");
 
app.get("/", (req, res) => {
  res.redirect("/users");
});
 
app.get("/users", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  console.log(users);
  res.render("listUsers", (data = users));
});
 
const PORT = process.env.PORT || 3000;
 
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

 

 

As you can see we are importing the express library and then we are starting the app at the port 5000 and then we are redirecting the user to the listUsers.ejs template when the user goes to the / route. And then we are reading the content of the api.json file. And then we are passing the json-server middleware to the express app. And here we need to pass the path of the json file that we need to make the backend api. And also we are passing the body-parser middleware

 

Now we need to create the api.json file and copy paste the following code

 

api.json

 

1
2
3
4
5
{
  "users": [
 
  ]
}

 

 

And then now we need to make the views folder and inside it we need to make the listUsers.ejs file and copy paste the following code

 

 

listUsers.ejs

 

 

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 class="text-center">JSON-Server Rest CRUD API in Express</h1>
        <form action="/users" method="post">
            <input class="form-control" type="text" name="name" placeholder="Enter name" required><br>
            <input class="form-control" type="number" name="age" placeholder="Enter age" required><br>
            <input class="form-control" type="text" name="country" placeholder="Enter country" required><br>
            <button class="btn btn-info">Add User</button>
        </form>
 
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Country</th>
                    <th>Edit User</th>
                    <th>Delete User</th>
                </tr>
            </thead>
            <tbody>
                <%if(data){%>
 
                    <%data.forEach((user)=> {%>
 
                        <tr>
                            <td>
                                <%=user.name%>
                            </td>
                            <td>
                                <%=user.age%>
                            </td>
                            <td>
                                <%=user.country%>
                            </td>
                            <td>
                                <a class="btn btn-primary" href="/edituser/<%=user.id%>">Edit User</button>
                            </td>
                            <td>
                                <a class="btn btn-danger" href="/deluser/<%=user.id%>">Delete User</a>
                            </td>
                        </tr>
 
 
                        <%})%>
 
                            <%}%>
            </tbody>
        </table>
        </div>
</body>
 
</html>

 

 

As you can see we are importing the bootstrap cdn at the top and then we have the form where we allow the user to create the new user where we allow the user to enter the name age and country and then we are making a post request to the /users route and then we are listing out all the users inside the table. Where we also have the edit and delete buttons.

 

 

 

 

And now we need to write the post request to add a new user inside the index.js file as shown below

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
app.post("/users", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  let user = {
    id:Date.now(),
    name:req.body.name,
    age:req.body.age,
    country:req.body.country
  }
  users.push(user);
  fs.writeFileSync("api.json", JSON.stringify({ users }));
  res.redirect('/users')
});

 

 

As you can see in the above code we have the post request and inside this we are getting the json data from the api.json file and then we are adding a new user which contains a new object which contains the id,name age and country. And then we are adding it to the array using the push() method and then we are appending the data using the fs module. And then we are redirecting to the /users route.

 

 

 

 

 

Updating the User Using Id

 

 

Now we will be updating  the details of the individual user using it’s id. When we click the edit button we will be going to the /edit/:id of the user.

 

 

JavaScript
1
2
3
4
5
app.get('/edituser/:id',(req,res) => {
    const users = JSON.parse(fs.readFileSync("api.json")).users;
    const user = users.find((u) => u.id === parseInt(req.params.id));
    res.render('editUser',{data:users,userdata:user})
})

 

 

And then inside the above code we are loading the editUser ejs template and here we are passing the data of the user which is updating. And now we need to create the views/editUser.ejs file and copy paste the following code

 

 

views/editUser.ejs

 

 

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
 
<body>
    <div class="container">
        <h1 class="text-center">JSON-Server Rest CRUD API in Express</h1>
        <form action="/edituser/<%=userdata.id%>" method="post">
            <input class="form-control" value="<%=userdata.name%>" type="text" name="name" placeholder="Enter name"
                required><br>
            <input class="form-control" value="<%=userdata.age%>" type="number" name="age" placeholder="Enter age"
                required><br>
            <input class="form-control" value="<%=userdata.country%>" type="text" name="country"
                placeholder="Enter country" required><br>
            <button class="btn btn-info">Update User</button>
        </form>
 
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Country</th>
                    <th>Edit User</th>
                    <th>Delete User</th>
                </tr>
            </thead>
            <tbody>
                <%if(data){%>
 
                    <%data.forEach((user)=> {%>
 
                        <tr>
                            <td>
                                <%=user.name%>
                            </td>
                            <td>
                                <%=user.age%>
                            </td>
                            <td>
                                <%=user.country%>
                            </td>
                            <td>
                                <a class="btn btn-primary" href="/edituser/<%=user.id%>">Edit User</button>
                            </td>
                            <td>
                                <a class="btn btn-danger" href="/deluser/<%=user.id%>">Delete User</a>
                            </td>
                        </tr>
 
 
                        <%})%>
 
                            <%}%>
            </tbody>
        </table>
    </div>
</body>
 
</html>

 

 

And now we need to make the post request to the /edituser/:id where we will be updating the details of the user using it’s id as shown below

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
app.post("/edituser/:id", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  const user = users.find((u) => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send("User not found");
  Object.assign(user, req.body);
  fs.writeFileSync("api.json", JSON.stringify({ users }));
  res.redirect('/users')
});

 

 

As you can see we are using the find method to get the user using it’s id which we are getting inside the params in the url. And then we are updating the details. And lastly we are redirecting the user to the /users/route.

 

 

 

 

 

Deleting Users Using it’s ID

 

 

Now we will be deleting the users using it’s id. And here we need to write the get request inside the index.js file. And here we are getting the id of the user and then we are using the splice() method to remove the user which matches the passed id from the params inside the url as shown below

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
app.get("/deluser/:id", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  const userIndex = users.findIndex((u) => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).send("User not found");
  users.splice(userIndex, 1);
  fs.writeFileSync("api.json", JSON.stringify({ users }));
  res.redirect('/users')
});

 

 

 

 

 

FULL SOURCE CODE

 

 

index.js

 

 

JavaScript
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const express = require("express");
const jsonServer = require("json-server");
const fs = require("fs");
const bodyparser = require("body-parser");
 
const app = express();
 
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
 
const jsonServerMiddleware = jsonServer.router("api.json");
app.use("/api", jsonServerMiddleware);
 
app.set("view engine", "ejs");
 
app.get("/", (req, res) => {
  res.redirect("/users");
});
 
app.get("/users", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  console.log(users);
  res.render("listUsers", (data = users));
});
 
app.post("/users", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  let user = {
    id:Date.now(),
    name:req.body.name,
    age:req.body.age,
    country:req.body.country
  }
  users.push(user);
  fs.writeFileSync("api.json", JSON.stringify({ users }));
  res.redirect('/users')
});
 
app.get('/edituser/:id',(req,res) => {
    const users = JSON.parse(fs.readFileSync("api.json")).users;
    const user = users.find((u) => u.id === parseInt(req.params.id));
    res.render('editUser',{data:users,userdata:user})
})
 
app.post("/edituser/:id", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  const user = users.find((u) => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send("User not found");
  Object.assign(user, req.body);
  fs.writeFileSync("api.json", JSON.stringify({ users }));
  res.redirect('/users')
});
 
app.get("/deluser/:id", (req, res) => {
  const users = JSON.parse(fs.readFileSync("api.json")).users;
  const userIndex = users.findIndex((u) => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).send("User not found");
  users.splice(userIndex, 1);
  fs.writeFileSync("api.json", JSON.stringify({ users }));
  res.redirect('/users')
});
 
const PORT = process.env.PORT || 3000;
 
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

 

Recent Posts

  • Android Java Project to Store,Read & Delete Data Using SharedPreferences Example
  • Android Java Project to Download Multiple Images From URL With Progressbar & Save it inside Gallery
  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme