π LAB SERIES: Web Architecture + Performance + Node.js
We’ll do 20 LABS total
π Starting with LAB 1–5 (Foundation + Tools)
π§ͺ π₯ LAB 1: Inspect HTTP Request (Chrome DevTools)
π― Goal
Understand how browser → server communication works
π ️ Steps
- Open Chrome
- Go to any website (example: google.com)
- Press F12 → Network tab
- Refresh page
π What You’ll See
- Request URL
- Method (GET)
- Status (200 OK)
- Response size
π From your PDF:
π Browser sends HTTP request → server responds
π‘ Output Understanding
GET / → Request
200 OK → Response
200 OK → Response
π§ͺ π₯ LAB 2: View Response Time (Performance Insight)
π― Goal
Understand why speed matters
π ️ Steps
- Open DevTools → Network
- Click any request
- Go to Timing tab
π Observe:
- DNS lookup time
- Connection time
- Response time
π From PDF:
π Even 100ms delay impacts revenue
π§ͺ π₯ LAB 3: Enable/Disable Cache
π― Goal
Understand caching impact
π ️ Steps
- Open DevTools → Network
- Tick Disable Cache
- Refresh page
π Compare:
Mode Speed Cache ON Fast Cache OFF Slow
| Mode | Speed |
|---|---|
| Cache ON | Fast |
| Cache OFF | Slow |
π From PDF:
π Cache reduces repeated requests
π§ͺ π₯ LAB 4: GZIP Compression Check
π― Goal
See real compression
π ️ Steps
- Open DevTools → Network
- Click request
- Check Headers → Content-Encoding
✅ Output
Content-Encoding: gzip
π From PDF:
π 100KB → 10KB after compression
π§ͺ π₯ LAB 5: Build Your First Node Server
π― Goal
Create backend server
π ️ Step 1: Install Node.js
π https://nodejs.org
Check:
node -v
π ️ Step 2: Create Project
mkdir lab5-server
cd lab5-server
code .
cd lab5-server
code .
π ️ Step 3: Create server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from Node Server π');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from Node Server π');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
π ️ Step 4: Run
node server.js
π Open browser:
http://localhost:3000
✅ Output
Hello from Node Server π
π Matches your Node.js PDF server example
π§ REAL UNDERSTANDING
What just happened?
Browser → Request → Node Server → Response → Browser
π You built:
✔ Presentation (browser)
✔ Logic (Node server)
✔ (Data layer coming next)
π― MINI CHALLENGE π₯
Modify code:
if (req.url === '/about') {
res.end('About Page');
} else {
res.end('Home Page');
}
π Test:
//about
π LAB 6–10 (REAL BACKEND + REST + MINI PROJECT)
π§ͺ π₯ LAB 6: Serve HTML Page (Frontend + Backend)
π― Goal
Connect Node server → HTML page
π ️ Step 1: Create index.html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
</head>
<body>
<h1>Welcome to My Web App π</h1>
</body>
</html>
π ️ Step 2: Update server.js
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
fs.readFile('index.html', (err, data) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
server.listen(3000);
▶️ Run
node server.js
π Open: http://localhost:3000
✅ Output
π Your HTML page loads
π Same concept as your PDF:
π Server reads file → sends response
π§ͺ π₯ LAB 7: Create JSON API (REST API)
π― Goal
Build API like real apps (Swiggy, Amazon)
π ️ Code
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/api/users') {
const users = [
{id: 1, name: "Rahul"},
{id: 2, name: "Amit"}
];
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(users));
}
});
server.listen(3000);
▶️ Test
π http://localhost:3000/api/users
✅ Output
[
{"id":1,"name":"Rahul"},
{"id":2,"name":"Amit"}
]
π From your Node PDF:
π JSON APIs are core of modern apps
π§ͺ π₯ LAB 8: Handle POST Request (Send Data)
π― Goal
Receive data from client
π ️ Code
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/data') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
console.log('Received:', body);
res.writeHead(200);
res.end('Data received');
});
}
});
server.listen(3000);
▶️ Test using terminal
curl -X POST http://localhost:3000/data -d "name=Gyan"
✅ Output
Received: name=Gyan
π Same event-driven concept from PDF
π§ͺ π₯ LAB 9: Create Simple Routing System
π― Goal
Handle multiple pages
π ️ Code
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.end('Home Page');
} else if (req.url === '/about') {
res.end('About Page');
} else if (req.url === '/contact') {
res.end('Contact Page');
} else {
res.end('404 Not Found');
}
});
server.listen(3000);
▶️ Test
-
/ -
/about -
/contact
π§ Learning
π This is basic Controller logic (MVC)
π§ͺ π₯ LAB 10: MINI PROJECT (Frontend + Backend)
π― Goal
Real system: User List App
π Project Structure
lab10-app/
│
├── server.js
├── index.html
π ️ Backend (server.js)
const http = require('http');
const users = [
{id: 1, name: "Rahul"},
{id: 2, name: "Amit"}
];
const server = http.createServer((req, res) => {
if (req.url === '/api/users') {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(users));
} else {
require('fs').readFile('index.html', (err, data) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
}
});
server.listen(3000);
π ️ Frontend (index.html)
<!DOCTYPE html>
<html>
<body>
<h1>User List</h1>
<ul id="list"></ul>
<script>
fetch('/api/users')
.then(res => res.json())
.then(data => {
const list = document.getElementById('list');
data.forEach(user => {
const li = document.createElement('li');
li.innerText = user.name;
list.appendChild(li);
});
});
</script>
</body>
</html>
▶️ Run
node server.js
π Open: http://localhost:3000
✅ Output
π User names displayed dynamically
π§ WHAT YOU BUILT
| Layer | Example |
|---|---|
| π¨ Frontend | HTML + JS |
| ⚙️ Backend | Node API |
| π Communication | REST API |
π This is 3-Tier Architecture in action
π LAB 11–20: Express + DB + Performance + Deployment
π§ͺ π₯ LAB 11: Install Express.js (Industry Standard)
π― Goal
Move from raw Node → Express (easy routing)
π ️ Step 1: Setup Project
mkdir lab11-express
cd lab11-express
npm init -y
npm install express
cd lab11-express
npm init -y
npm install express
π ️ Step 2: Create server.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express π');
});
app.listen(3000, () => console.log('Server running'));
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express π');
});
app.listen(3000, () => console.log('Server running'));
▶️ Run
node server.js
π Open: http://localhost:3000
π§ Why Express?
-
Cleaner routing
-
Middleware support
-
Faster development
π§ͺ π₯ LAB 12: Middleware (VERY IMPORTANT)
π― Goal
Understand request processing pipeline
π ️ Code
const express = require('express');
const app = express();
// Middleware
app.use((req, res, next) => {
console.log('Request received:', req.url);
next(); // move to next
});
app.get('/', (req, res) => {
res.send('Home Page');
});
app.listen(3000);
const app = express();
// Middleware
app.use((req, res, next) => {
console.log('Request received:', req.url);
next(); // move to next
});
app.get('/', (req, res) => {
res.send('Home Page');
});
app.listen(3000);
π§ Concept
Request → Middleware → Route → Response
π Like security check before entry
π§ͺ π₯ LAB 13: Connect MongoDB
π― Goal
Add database layer
π ️ Install
npm install mongoose
π ️ Code
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/testDB')
.then(() => console.log('DB Connected'));
mongoose.connect('mongodb://127.0.0.1:27017/testDB')
.then(() => console.log('DB Connected'));
π§ From your PDF:
π Data layer = persistence system (DB)
π§ͺ π₯ LAB 14: CRUD API (REAL BACKEND)
π― Goal
Create full API
π ️ Model
const User = mongoose.model('User', {
name: String
});
name: String
});
π ️ Routes
// CREATE
app.post('/users', async (req, res) => {
const user = new User({ name: "Rahul" });
await user.save();
res.send(user);
});
// READ
app.get('/users', async (req, res) => {
const users = await User.find();
res.send(users);
});
app.post('/users', async (req, res) => {
const user = new User({ name: "Rahul" });
await user.save();
res.send(user);
});
// READ
app.get('/users', async (req, res) => {
const users = await User.find();
res.send(users);
});
π§ This is:
π REST API (GET, POST)
π§ͺ π₯ LAB 15: Test API (Postman)
π― Goal
Test backend APIs
π ️ Steps
-
Install Postman
-
Test:
-
GET
/users
-
POST
/users
-
GET
/users -
POST
/users
π§ Output
π JSON responses
π§ͺ π₯ LAB 16: Authentication (Basic Login)
π― Goal
Secure your app
π ️ Code
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === '1234') {
res.send('Login success');
} else {
res.send('Invalid credentials');
}
});
const { username, password } = req.body;
if (username === 'admin' && password === '1234') {
res.send('Login success');
} else {
res.send('Invalid credentials');
}
});
π§ Real-world:
π Used in banking, apps, portals
π§ͺ π₯ LAB 17: Load Balancing (Scaling)
π― Goal
Handle multiple users
π§ From your PDF:
π Multiple servers share load
π ️ Concept
User → Load Balancer → Server1 / Server2
π ️ Node Cluster Example
const cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.fork();
} else {
require('./server');
}
if (cluster.isMaster) {
cluster.fork();
cluster.fork();
} else {
require('./server');
}
π§ͺ π₯ LAB 18: Performance Optimization
π― Goal
Make app fast
π§ Techniques (from PDF)
✔ GZIP
✔ Caching
✔ Reduce requests
✔ Minify files
π ️ Example (Compression)
npm install compression
const compression = require('compression');
app.use(compression());
app.use(compression());
π§ͺ π₯ LAB 19: Deploy App (Cloud)
π― Goal
Make app live
π ️ Options
-
Render
-
Railway
-
AWS (advanced)
π ️ Steps (Render Example)
-
Push code to GitHub
-
Connect to Render
-
Deploy
π Output
π Your app live URL
π§ͺ π₯ LAB 20: FINAL PROJECT π₯
π― Build:
π Full User Management System
π Structure
project/
├── backend/
│ ├── server.js
│ ├── routes/
│ ├── models/
│
├── frontend/
│ ├── index.html
│ ├── app.js
├── backend/
│ ├── server.js
│ ├── routes/
│ ├── models/
│
├── frontend/
│ ├── index.html
│ ├── app.js
π₯ Features
✔ Add User
✔ View Users
✔ Delete User
✔ API Backend
✔ Database Storage
π§ Architecture Used
Concept Used 3-Tier ✔ MVC ✔ REST ✔ Node ✔ Performance ✔
| Concept | Used |
|---|---|
| 3-Tier | ✔ |
| MVC | ✔ |
| REST | ✔ |
| Node | ✔ |
| Performance | ✔ |
π― FINAL RESULT (YOU NOW KNOW)
π₯ Full Web Architecture
π₯ Backend APIs
π₯ Database
π₯ Performance tuning
π₯ Deployment
π π₯ FULL PROJECT: User Management System
π π¦ Project Structure (IMPORTANT)
user-management-app/
│
├── backend/
│ ├── server.js
│ ├── db.js
│ ├── models/
│ │ └── User.js
│ ├── routes/
│ │ └── userRoutes.js
│
├── frontend/
│ ├── index.html
│ ├── script.js
│ ├── style.css
│
├── package.json
│
├── backend/
│ ├── server.js
│ ├── db.js
│ ├── models/
│ │ └── User.js
│ ├── routes/
│ │ └── userRoutes.js
│
├── frontend/
│ ├── index.html
│ ├── script.js
│ ├── style.css
│
├── package.json
⚙️ STEP 1: Setup Project
mkdir user-management-app
cd user-management-app
mkdir backend frontend
cd backend
npm init -y
npm install express mongoose cors body-parser
cd user-management-app
mkdir backend frontend
cd backend
npm init -y
npm install express mongoose cors body-parser
π§ STEP 2: Database Connection (db.js)
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/userDB')
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
mongoose.connect('mongodb://127.0.0.1:27017/userDB')
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
π¦ STEP 3: Model (models/User.js)
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String
});
module.exports = mongoose.model('User', userSchema);
const userSchema = new mongoose.Schema({
name: String,
email: String
});
module.exports = mongoose.model('User', userSchema);
π STEP 4: Routes (routes/userRoutes.js)
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// CREATE
router.post('/', async (req, res) => {
const user = new User(req.body);
await user.save();
res.json(user);
});
// READ
router.get('/', async (req, res) => {
const users = await User.find();
res.json(users);
});
// DELETE
router.delete('/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.json({message: 'Deleted'});
});
module.exports = router;
const router = express.Router();
const User = require('../models/User');
// CREATE
router.post('/', async (req, res) => {
const user = new User(req.body);
await user.save();
res.json(user);
});
// READ
router.get('/', async (req, res) => {
const users = await User.find();
res.json(users);
});
// DELETE
router.delete('/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.json({message: 'Deleted'});
});
module.exports = router;
π STEP 5: Server (server.js)
const express = require('express');
const app = express();
require('./db');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const userRoutes = require('./routes/userRoutes');
app.use('/api/users', userRoutes);
app.listen(5000, () => {
console.log('Server running on http://localhost:5000');
});
const app = express();
require('./db');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const userRoutes = require('./routes/userRoutes');
app.use('/api/users', userRoutes);
app.listen(5000, () => {
console.log('Server running on http://localhost:5000');
});
π¨ STEP 6: Frontend (frontend/index.html)
<!DOCTYPE html>
<html>
<head>
<title>User Management</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>User Management π</h1>
<input id="name" placeholder="Enter name">
<input id="email" placeholder="Enter email">
<button onclick="addUser()">Add User</button>
<ul id="userList"></ul>
<script src="script.js"></script>
</body>
</html>
<html>
<head>
<title>User Management</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>User Management π</h1>
<input id="name" placeholder="Enter name">
<input id="email" placeholder="Enter email">
<button onclick="addUser()">Add User</button>
<ul id="userList"></ul>
<script src="script.js"></script>
</body>
</html>
⚡ STEP 7: Frontend Logic (frontend/script.js)
const API = 'http://localhost:5000/api/users';
// Load users
function loadUsers() {
fetch(API)
.then(res => res.json())
.then(data => {
const list = document.getElementById('userList');
list.innerHTML = '';
data.forEach(user => {
const li = document.createElement('li');
li.innerHTML = `
${user.name} (${user.email})
<button onclick="deleteUser('${user._id}')">Delete</button>
`;
list.appendChild(li);
});
});
}
// Add user
function addUser() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
fetch(API, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name, email})
}).then(() => loadUsers());
}
// Delete user
function deleteUser(id) {
fetch(`${API}/${id}`, { method: 'DELETE' })
.then(() => loadUsers());
}
// Initial load
loadUsers();
// Load users
function loadUsers() {
fetch(API)
.then(res => res.json())
.then(data => {
const list = document.getElementById('userList');
list.innerHTML = '';
data.forEach(user => {
const li = document.createElement('li');
li.innerHTML = `
${user.name} (${user.email})
<button onclick="deleteUser('${user._id}')">Delete</button>
`;
list.appendChild(li);
});
});
}
// Add user
function addUser() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
fetch(API, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name, email})
}).then(() => loadUsers());
}
// Delete user
function deleteUser(id) {
fetch(`${API}/${id}`, { method: 'DELETE' })
.then(() => loadUsers());
}
// Initial load
loadUsers();
π¨ STEP 8: Styling (frontend/style.css)
body {
font-family: Arial;
padding: 20px;
}
input {
margin: 5px;
padding: 5px;
}
button {
margin: 5px;
padding: 5px;
background: green;
color: white;
}
li {
margin: 10px 0;
}
font-family: Arial;
padding: 20px;
}
input {
margin: 5px;
padding: 5px;
}
button {
margin: 5px;
padding: 5px;
background: green;
color: white;
}
li {
margin: 10px 0;
}
▶️ STEP 9: RUN PROJECT
Start Backend
cd backend
node server.js
node server.js
Start Frontend
π Open:
frontend/index.html
✅ FINAL OUTPUT
✔ Add User
✔ View Users
✔ Delete User
✔ Data stored in MongoDB
π§ ARCHITECTURE YOU BUILT
Frontend (HTML + JS)
↓
REST API (Express)
↓
Database (MongoDB)
↓
REST API (Express)
↓
Database (MongoDB)
π This is exactly 3-Tier Architecture from your PDF
No comments:
Post a Comment