Hereβs how you can complete TASK 7: Working with Express step by step:
---
π§ Step 1: Set Up the Project
mkdir user-api-ejs
cd user-api-ejs
npm init -y
npm install express ejs body-parser
---
π Project Structure
user-api-ejs/
βββ views/
β βββ users.ejs
βββ routes/
β βββ users.js
βββ app.js
π¦ Step 2: Create the Express Server (app.js)
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const usersRouter = require('./routes/users');
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/api/users', usersRouter); // REST API
app.use('/users', usersRouter); // For EJS view
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
---
π Step 3: Users API Routes (routes/users.js)
const express = require('express');
const router = express.Router();
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
];
// READ all users (API)
router.get('/', (req, res) => {
if (req.originalUrl.startsWith('/api')) {
res.json(users);
} else {
res.render('users', { users });
}
});
// CREATE a new user
router.post('/', (req, res) => {
const { name, email } = req.body;
const newUser = { id: users.length + 1, name, email };
users.push(newUser);
res.json(newUser);
});
// UPDATE a user
router.put('/:id', (req, res) => {
const id = parseInt(req.params.id);
const { name, email } = req.body;
const user = users.find(u => u.id === id);
if (user) {
user.name = name;
user.email = email;
res.json(user);
} else {
res.status(404).json({ message: 'User not found' });
}
});
// DELETE a user
router.delete('/:id', (req, res) => {
const id = parseInt(req.params.id);
users = users.filter(u => u.id !== id);
res.json({ message: 'User deleted' });
});
module.exports = router;
πΌοΈ Step 4: Create EJS Template (views/users.ejs)
<!DOCTYPE html>
<html>
<head>
<title>Users Table</title>
<style>
table {
width: 60%;
border-collapse: collapse;
margin: 20px auto;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2 style="text-align: center;">Users List</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>
π§ͺ Step 5: Test in Postman
Test these endpoints:
GET http://localhost:3000/api/users β Get all users (JSON)
POST http://localhost:3000/api/users β Add user (Body: name, email)
PUT http://localhost:3000/api/users/:id β Update user by ID
DELETE http://localhost:3000/api/users/:id β Delete user by ID
Visit http://localhost:3000/users to see the data in table form via EJS.