//1. Create a custom API for Users data and add different endpoints in express server to perform CRUD operations on the API. Test the endpoints using POSTMAN.
//2. Use EJS view-engine to display the dynamic response. Display the data read from REST API in the form of a table in EJS.
const express=require("express");
const app=express();
app.use(express.json());
app.set("view engine","ejs");
let users=[
{id:1,name:"Abhi",email:"abhi@gmail.com"},
{ id:2,name:"Vars",email:"Vars@gmail.com"}
]
app.get("/users",(req,res)=>{
res.render('users',{users});
})
app.get("/users/:id",(req,res)=>{
const user=users.find(u=>u.id===parseInt(req.params.id));
if(!user) return res.json({message:"No user"});
res.json(user);
})
app.post("/users",(req,res)=>{
const {name,email}=req.body;
const newUser={
id:users.length+1,
name:name,
email:email
};
users.push(newUser);
res.render('users',{users});
});
app.put("/users/:id",(req,res)=>{
const user=users.find(u=>u.id===parseInt(req.params.id));
if(!user) return res.json({message:"No user"});
user.name=req.body.name;
user.email=req.body.email;
res.json(user);
})
app.delete("/users/:id",(req,res)=>{
users = users.filter(u => u.id != req.params.id);
res.render('users',{users});
})
app.listen(3000,()=>{
console.log("Server listening");
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Table</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<%users.forEach(user=>{ %>
<tr>
<td><%=user.id %></td>
<td><%=user.name %></td>
<td><%=user.email %></td>
</tr>
<% }) %>
</tbody>
</table>
</body>
</html>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter