Full Stack Material
Full Stack Material
T D SAI KISHORE
Assistant Professor
Department
of
Mechanical Engineering
1
Full Stack Development (MERN)-CS631PE Department of CSE
Syllabus
UNIT-I Introduction to Full Stack Development: Understanding the Basic Web Development
Framework- User, Browser, Webserver, Backend Services, Full Stack Components - Node.js, MongoDB,
Express, React, Angular. Java Script Fundamentals, NodeJS- Understanding Node.js, Installing Node.js,
Working with Node Packages, creating a Node.js Application, Understanding the Node.js Event Model,
Adding Work to the Event Queue, Implementing Callbacks.
UNIT-II Node.js:
Working with JSON, Using the Buffer Module to Buffer Data, Using the Stream Module to Stream Data,
Accessing the File System from Node.js- Opening, Closing, Writing, Reading Files and other File System
Tasks. Implementing HTTP Services in Node.js- Processing URLs, Processing Query Strings and Form
Parameters, Understanding Request, Response, and Server Objects, Implementing HTTP Clients and
Servers in Node.js, Implementing HTTPS Servers and Clients. Using Additional Node.js Modules-Using
the OS Module, Using the util Module, Using the DNS Module, Using the crypto Module.
UNIT-III MongoDB:
Need of NoSQL, Understanding MongoDB, MongoDB Data Types, Planning Your Data Model, Building
the MongoDB Environment, Administering User Accounts, Configuring Access Control, Administering
Databases, Managing Collections, Adding the MongoDB Driver to Node.js, Connecting to MongoDB
from Node.js, Understanding the Objects Used in the MongoDB Node.js Driver, Accessing and
Manipulating Databases, Accessing and Manipulating Collections
UNIT-V React:
Need of React, Simple React Structure, The Virtual DOM, React Components, Introducing React
Components, Creating Components in React, Data and Data Flow in React, Rendering and Life Cycle
Methods in React, working with forms in React, integrating third party libraries, Routing in React
2
Full Stack Development (MERN)-CS631PE Department of CSE
UNIT-1
Understanding the Basic Web Development Framework
Web development frameworks provide a structured approach to building web applications, making
development faster, more efficient, and scalable. These frameworks handle routine tasks such as
routing, authentication, and database interaction, allowing developers to focus on business logic.
1. What is a Web Development Framework?
A web development framework is a collection of libraries, tools, and best practices that simplify the
development of web applications. It provides a foundation that developers can build upon instead of
coding everything from scratch.
Types of Web Development Frameworks
1. Front-end Frameworks – Used for UI development (e.g., React.js, Angular, Vue.js).
2. Back-end Frameworks – Used for server-side logic (e.g., Express.js, Spring Boot, Django).
3. Full-stack Frameworks – Include both front-end and back-end capabilities (e.g., Next.js,
Meteor).
2. Front-End Frameworks
Front-end frameworks help developers create interactive and responsive user interfaces.
Common Front-End Frameworks
Framework Language Features
React.js JavaScript Component-based, Virtual DOM, Hooks
Angular TypeScript MVC, Two-way Data Binding, Dependency Injection
Vue.js JavaScript Reactive Data Binding, Component-based
Core Concepts in Front-End Development
• HTML (Hypertext Markup Language) – Structure of a web page.
• CSS (Cascading Style Sheets) – Styling and layout.
• JavaScript (JS) – Interactivity and dynamic behaviour.
Tools for Front-End Development
• Webpack, Babel – Bundling and transfilling code.
• Tailwind CSS, Bootstrap – Pre-built styling frameworks.
• React Router – Handles navigation in React applications.
3. Back-End Frameworks
Back-end frameworks manage server-side logic, database interactions, and authentication.
3
Full Stack Development (MERN)-CS631PE Department of CSE
4
Full Stack Development (MERN)-CS631PE Department of CSE
Detailed Explanation of Full-Stack Components (Node.js, MongoDB, Express, React, Angular) &
JavaScript Fundamentals
Full-stack development refers to the combination of both front-end and back-end technologies to build
a complete web application. This guide will cover essential full-stack components, including Node.js,
MongoDB, Express.js, React, Angular, and JavaScript fundamentals.
1. JavaScript Fundamentals
JavaScript is the core programming language used for full-stack development. Understanding its
fundamentals is essential before diving into frameworks like Node.js, React, Angular, and Express.
Key JavaScript Concepts
Concept Explanation
Variables Use var, let, and const to declare variables.
JavaScript has primitive types (string, number, boolean, null, undefined)
Data Types
and objects.
Define functions using function declarations, expressions, and arrow
Functions
functions (()=>{}).
Includes let/const, template literals, spread/rest operators,
ES6 Features
destructuring, promises, and async/await.
Methods like document.getElementById(), event listeners to
DOM Manipulation
manipulate HTML elements.
Event Handling Handling user interactions using addEventListener().
Uses callbacks, Promises, and async/await for handling async
Asynchronous JS
operations.
Closures & Scope Understanding block scope, function scope.
Object-Oriented
JavaScript supports prototype-based inheritance and ES6 class syntax.
Programming (OOP)
Modules Use import and export to organize code in ES6.
Error Handling Using try...catch for exception handling.
2. Data Types
JavaScript has primitive types (string, number, boolean, null, undefined) and objects.
let str = "Hello"; // String
let num = 42; // Number
let isTrue = true; // Boolean
let empty = null; // Null
let notDefined; // Undefined
let obj = { key: "value" }; // Object
3. Functions
Define functions using function declarations, expressions, and arrow functions.
function regularFunction() { return "Hello"; } // Function declaration
const functionExpression = function () { return "Hello"; }; // Function expression
5
Full Stack Development (MERN)-CS631PE Department of CSE
4. ES6 Features
Modern JavaScript features.
let name = "John";
console.log(`Hello, ${name}!`); // Template literals
let arr = [1, 2, 3];
let newArr = [...arr, 4]; // Spread operator
const person = { firstName: "John", lastName: "Doe" };
const { firstName, lastName } = person; // Object destructuring
const fetchData = async () => {
let data = await fetch("https://api.example.com");
return data.json();
}; // Async/Await
5. DOM Manipulation
Modify HTML elements dynamically.
document.getElementById("demo").innerText = "Hello, World!";
document.querySelector(".my-class").style.color = "red";
6. Event Handling
Handle user interactions.
document.getElementById("btn").addEventListener("click", () => {
alert("Button Clicked!");
});
7. Asynchronous JS
Use callbacks, Promises, and async/await.
setTimeout(() => console.log("Executed after 2 seconds"), 2000); // Callback
fetch("https://api.example.com")
.then(response => response.json()) // Promise
.then(data => console.log(data))
.catch(error => console.error(error));
6
Full Stack Development (MERN)-CS631PE Department of CSE
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
10. Modules
Organize code using import and export.
// module.js
export const greet = () => console.log("Hello!");
// main.js
import { greet } from "./module.js";
greet();
2. Node.js
Node.js is a runtime environment that allows JavaScript to run on the server-side. It is built on the V8
engine (same engine used in Chrome).
Why Use Node.js?
• Non-blocking, event-driven architecture
• Uses JavaScript for both front-end and back-end
• Fast execution speed due to the V8 engine
• Large ecosystem with NPM packages
Core Features of Node.js
7
Full Stack Development (MERN)-CS631PE Department of CSE
Feature Explanation
Single-threaded Event
Handles multiple requests asynchronously using an event-driven model.
Loop
Modules Built-in modules (fs, http, path), and third-party modules via npm.
Express.js A lightweight framework to build APIs and web applications.
File System Access Read and write files using the fs module.
Streams Handles large files efficiently.
Web Sockets Real-time communication using socket.io.
3. Express.js
Express.js is a lightweight Node.js framework for building web applications and APIs.
Why Use Express?
• Simplifies routing and request handling
• Middleware support for logging, authentication, and more
• Supports RESTful APIs
Core Features of Express.js
Feature Explanation
Routing Define application endpoints (app.get(), app.post()).
Middleware Functions that process requests (e.g., authentication, logging).
Template Engines Use EJS, Handlebars, or Pug for rendering views.
Static File Serving Serve static files like CSS and images.
Example: Simple Express.js Server
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server running on port 3000');
});
4. MongoDB
MongoDB is a NoSQL database that stores data in JSON-like documents.
Why Use MongoDB?
8
Full Stack Development (MERN)-CS631PE Department of CSE
5. React.js
React.js is a popular JavaScript library for building UI components.
Why Use React?
• Component-based architecture
• Virtual DOM for efficient rendering
• Supports hooks and functional components
function App () {
return <h1>Hello, React! </h1>;
}
export default App;
6. Angular
Angular is a TypeScript-based framework for building web applications.
Why Use Angular?
• Built-in support for MVC architecture
• Two-way data binding
• Dependency Injection
9
Full Stack Development (MERN)-CS631PE Department of CSE
@Component({
selector: 'app-root',
template: `<h1>Hello, Angular!</h1>`
})
export class AppComponent {}
Install Node.js
Step 1: Download Node.js
1. Go to the official Node.js website.
2. You will see two versions:
o LTS (Long Term Support): Recommended for most users and production
environments.
o Current: The latest features, but may not be as stable.
3. Click on the appropriate version for your operating system (Windows, macOS, or Linux).
10
Full Stack Development (MERN)-CS631PE Department of CSE
3. Installing Packages
A. Installing a Package Globally
Some tools (like nodemon) are installed globally to be used system-wide:
npm install -g nodemon
You can now use nodemon from the terminal.
B. Installing a Package Locally
To install a package only for a specific project (e.g., express):
npm install express
This adds express to node_modules and updates package.json.
C. Installing Dev Dependencies
11
Full Stack Development (MERN)-CS631PE Department of CSE
For packages needed only during development (e.g., testing tools like jest):
npm install --save-dev jest
These are saved under devDependencies in package.json.
4. Using Installed Packages
After installing express, create a file (server.js) and use it:
const express = require('express');
const app = express();
5. Managing Packages
A. Checking Installed Packages
List installed dependencies:
npm list
List globally installed packages:
npm list -g --depth=0
B. Updating Packages
To update all dependencies to the latest compatible versions:
npm update
To update a specific package:
npm update express
C. Removing a Package
Uninstall a package:
npm uninstall express
If removing a dev dependency:
npm uninstall jest --save-dev
7. Running Scripts
Define scripts inside package.json:
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
12
Full Stack Development (MERN)-CS631PE Department of CSE
console.log('Start');
setTimeout(() => {
console.log('Task added to Event Queue');
}, 2000);
console.log('End');
Execution Flow:
1. Start is printed.
13
Full Stack Development (MERN)-CS631PE Department of CSE
3. Implementing Callbacks
A callback is a function that is passed as an argument to another function and is executed when an
asynchronous operation completes.
Example: Callback in File Reading
const fs = require('fs');
console.log('Start');
console.log('End');
Execution Flow:
1. Start is printed.
2. fs.readFile() starts reading the file but doesn’t block execution.
3. End is printed immediately.
4. Once the file read completes, the callback executes and prints File Content.
Output:
Start
End
File Content: <content of file.txt>
The Event Loop is the core of Node.js’s asynchronous behavior. It continuously checks the Event Queue
for pending tasks and executes them.
Event Loop Phases:
1. Timers → Executes setTimeout() and setInterval() callbacks.
2. I/O Callbacks → Executes callbacks from completed I/O operations (like fs.readFile()).
3. Idle & Prepare → Internal processing.
4. Poll → Fetches new I/O events, waiting for new tasks.
5. Check → Executes setImmediate() callbacks.
6. Close Callbacks → Executes close event callbacks (like socket.on('close')).
14
Full Stack Development (MERN)-CS631PE Department of CSE
process.nextTick(() => {
console.log('Next Tick Callback');
});
console.log('End');
Output:
Start
End
Next Tick Callback
process.nextTick() ensures the callback runs before any I/O operations or setTimeout().
console.log('End');
Output: (Order may vary)
Start
End
setImmediate Callback
setTimeout Callback
Why?
• setImmediate(): executes after the poll phase.
• setTimeout(0): executes after a minimal delay but still waits for the poll phase to clear.
emitter.emit('greet', 'Alice');
Output:
Hello, Alice!
Example: Handling Multiple Event Listeners
emitter.on('data', (msg) => console.log(`Listener 1: ${msg}`));
emitter.on('data', (msg) => console.log(`Listener 2: ${msg}`));
15
Full Stack Development (MERN)-CS631PE Department of CSE
readFiles();
Advantages of Promises:
• Avoids deep nesting.
• Improves readability.
• Easier error handling using try...catch.
Conclusion
• Node.js Event Model allows non-blocking execution.
• Event Queue stores asynchronous tasks.
• Callbacks execute when an operation completes.
• Event Loop efficiently manages queued tasks.
• Promises & async/await simplify handling asynchronous code.
Web References
1. https://www.geeksforgeeks.org/nodejs/?ref=lbp
2. https://nodejs.org/api/fs.html
3. https://www.tpointtech.com/nodejs-file-system
4. https://www.geeksforgeeks.org/mern-stack/
16
Full Stack Development (MERN)-CS631PE Department of CSE
UNIT-III
MongoDB stores data using BSON (Binary JSON), which supports a variety of data types
beyond standard JSON. Here are some key MongoDB data types:
• String: Used for storing text data (UTF-8 format).
• Integer: Supports both 32-bit and 64-bit signed integers.
• Double: Stores floating-point numbers.
• Boolean: Represents true or false values.
• Null: Represents missing or undefined values.
• ObjectId: A unique identifier for documents.
• Date: Stores date and time values
Planning your data model in MongoDB is crucial for optimizing performance and
scalability. Since MongoDB is a document-oriented NoSQL database, its schema
design differs significantly from relational databases. Here are some key
considerations:
1. Understand Your Application's Workload
• Identify how your application queries and updates data.
• Optimize for read-heavy or write-heavy operations.
2. Choose Between Embedded vs. Normalized Data Models
• Embedded Model: Stores related data within a single document, improving
read performance but potentially increasing redundancy.
• Normalized Model: Uses references between documents, reducing duplication
but requiring additional queries.
3. Apply Schema Design Patterns
• Bucket Pattern: Groups related data into a single document to reduce query
overhead.
• Extended Reference Pattern: Stores frequently accessed data within a
document while keeping detailed data in separate collections.
4. Indexing for Performance
• Use indexes to speed up queries but avoid excessive indexing, which can
impact write performance.
5. Plan for Scalability
• Consider sharding strategies if your dataset grows significantly.
You can explore more details in the MongoDB documentation.
17
Full Stack Development (MERN)-CS631PE Department of CSE
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
This creates an admin user with privileges to manage users across all databases.
2. Assigning Roles
MongoDB provides built-in roles such as:
• read: Allows read-only access.
• readWrite: Grants permission to read and write data.
• dbAdmin: Enables database administration tasks.
• userAdmin: Allows user management.
• clusterAdmin: Grants control over cluster-wide operations.
You can also create custom roles using db.createRole().
3. Listing Users
To view existing users in a database:
db.getUsers()
4. Updating User Credentials
To change a user's password:
db.changeUserPassword("adminUser", "newSecurePassword")
5. Deleting a User
To remove a user:
db.dropUser("adminUser")
Configuring access control in MongoDB ensures that only authorized users can interact with
the database. Here’s how you can set it up:
1. Enable Authentication
MongoDB requires authentication to restrict access. Start MongoDB with the --auth flag:
mongod --auth --port 27017 --dbpath /data/db
This ensures that users must authenticate before accessing the database.
2. Create an Admin User
Use the createUser() method to add an admin user:
use admin
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
This user will have privileges to manage other users.
3. Assign Roles
MongoDB provides built-in roles such as:
• read: Allows reading data.
• readWrite: Allows reading and writing data.
• dbAdmin: Grants database administration privileges.
• userAdmin: Allows managing users.
You can also create custom roles using createRole().
18
Full Stack Development (MERN)-CS631PE Department of CSE
4. Configure IP Whitelisting
Restrict access to trusted IPs by modifying the mongod.conf file:
net:
bindIp: 127.0.0.1,192.168.1.100
This ensures only specified IPs can connect.
5. Use TLS/SSL for Secure Connections
Enable TLS/SSL encryption to protect data in transit:
mongod --sslMode requireSSL --sslPEMKeyFile /etc/ssl/mongodb.pem
Managing collections in MongoDB involves creating, updating, deleting, and querying data
efficiently. Here’s a breakdown:
1. Creating a Collection
MongoDB automatically creates collections when you insert data, but you can explicitly create
one using:
db.createCollection("users")
You can also specify options like validation rules.
2. Inserting Documents
Add a single document:
db.users.insertOne({ name: "Sai", age: 25 })
Insert multiple documents:
db.users.insertMany([{ name: "Kishore", age: 30 }, { name: "Aditi", age: 28 }])
3. Querying Data
Find all documents:
db.users.find({})
Find specific documents:
db.users.find({ age: { $gt: 25 } })
4. Updating Documents
Modify a single document:
db.users.updateOne({ name: "Sai" }, { $set: { age: 26 } })
Update multiple documents:
db.users.updateMany({}, { $inc: { age: 1 } })
5. Deleting Documents
Remove a single document:
db.users.deleteOne({ name: "Sai" })
Delete multiple documents:
db.users.deleteMany({ age: { $lt: 25 } })
6. Dropping a Collection
To delete an entire collection:
db.users.drop()
To connect Node.js to MongoDB, follow these steps:
1. Install the MongoDB Driver
Run the following command in your Node.js project:
npm install mongodb
This installs the official MongoDB Node.js driver.
19
Full Stack Development (MERN)-CS631PE Department of CSE
2. Connect to MongoDB
Create a connection using the MongoDB client:
const { MongoClient } = require("mongodb");
mongoose.connect("mongodb://localhost:27017/myDatabase", {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("Connected to MongoDB!"))
.catch(err => console.error("Connection error:", err));
Mongoose provides schema validation and easier data handling.
Understanding the Objects Used in the MongoDB Node.js Driver
The MongoDB Node.js driver provides several key objects to interact with MongoDB efficiently. Here
are the most important ones:
1. MongoClient
The MongoClient object is used to establish a connection to MongoDB.
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017");
It allows you to connect to a MongoDB instance and perform operations.
2. Db
The Db object represents a specific database within MongoDB.
const db = client.db("myDatabase");
You use this object to interact with collections and execute queries.
3. Collection
The Collection object represents a collection within a database.
const users = db.collection("users");
It provides methods for inserting, updating, deleting, and querying documents.
4. Cursor
A Cursor object is returned when querying data, allowing iteration over results.
const cursor = users.find({ age: { $gt: 25 } });
cursor.forEach(doc => console.log(doc));
20
Full Stack Development (MERN)-CS631PE Department of CSE
Manipulating Databases
• Create a new database: Just switch to it and insert data.
• use newDB
• db.myCollection.insertOne({ name: "Sai" })
• Drop a database:
• db.dropDatabase()
21
Full Stack Development (MERN)-CS631PE Department of CSE
Unit -2
1. Working with JSON in Node.js
JSON (JavaScript Object Notation) is a lightweight format for storing and transporting data. In
Node.js, it's commonly used for configuration files, APIs, and data exchange.
Key Operations:
• JSON.stringify(): Converts a JavaScript object to a JSON string.
• JSON.parse(): Converts a JSON string back to a JavaScript object.
Example:
const user = { name: "Sai", age: 25 };
22
Full Stack Development (MERN)-CS631PE Department of CSE
readStream.on("end", () => {
console.log("Finished reading.");
});
Writing to a File with Streams:
const writeStream = fs.createWriteStream("output.txt");
writeStream.write("Hello, Sai!\n");
writeStream.write("Streaming is efficient.\n");
writeStream.end();
This approach is memory-efficient and ideal for handling large datasets or real-time
applications like video streaming or chat servers.
3. Writing to a File
Using fs.writeFile()
Overwrites the file or creates it if it doesn’t exist.
fs.writeFile("example.txt", "Hello, Sai!", err => {
if (err) throw err;
console.log("File written successfully!");
});
Using fs.appendFile()
Adds content to the end of the file.
fs.appendFile("example.txt", "\nAppended line.", err => {
if (err) throw err;
console.log("Content appended!");
});
23
Full Stack Development (MERN)-CS631PE Department of CSE
5. Closing a File
When using fs.open(), you can close the file descriptor manually:
fs.open("example.txt", "r", (err, fd) => {
if (err) throw err;
console.log("File opened!");
6. Deleting a File
Using fs.unlink()
fs.unlink("example.txt", err => {
if (err) throw err;
console.log("File deleted!");
});
24
Full Stack Development (MERN)-CS631PE Department of CSE
Implementing HTTP services in Node.js involves handling requests, processing URLs, and
responding to clients efficiently. Let’s break it down step by step:
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• http.createServer() creates a server.
• res.writeHead(200, { "Content-Type": "text/plain" }) sets the response header.
• res.end() sends the response and closes the connection.
• server.listen(3000) starts the server on port 3000.
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• url.parse(req.url, true) extracts query parameters.
• parsedUrl.query.name retrieves the name parameter from the URL.
• Example request: http://localhost:3000/?name=Sai → Response: "Hello, Sai!"
25
Full Stack Development (MERN)-CS631PE Department of CSE
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• pathname === "/about" serves the About page.
• pathname === "/contact" serves the Contact page.
• Default response serves the Home page.
4. Handling POST Requests
For handling form submissions or API requests, use req.on("data") to process incoming data.
Example: Handling POST Data
const http = require("http");
req.on("end", () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received Data: ${body}`);
});
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Only POST requests are allowed.");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
26
Full Stack Development (MERN)-CS631PE Department of CSE
});
• req.on("data", chunk => { body += chunk; }) collects incoming data.
• req.on("end", () => { res.end(body); }) sends the processed data back.
Processing query strings and form parameters in Node.js is essential for handling user input
in web applications. Let’s break it down step by step with examples.
1. Understanding Query Strings
Query strings are appended to URLs after a ? and contain key-value pairs separated by &.
Example URL with Query String:
http://localhost:3000/?name=Sai&age=25
Here, name=Sai and age=25 are query parameters.
Extracting Query Parameters in Node.js
Using the built-in url module:
const http = require("http");
const url = require("url");
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• url.parse(req.url, true) extracts query parameters.
• parsedUrl.query holds the key-value pairs.
27
Full Stack Development (MERN)-CS631PE Department of CSE
The querystring module provides utilities for parsing and formatting query strings.
Parsing Query Strings
const querystring = require("querystring");
console.log(parsedQuery.name); // Sai
console.log(parsedQuery.age); // 25
Stringifying Objects into Query Strings
const obj = { name: "Sai", age: 25 };
const queryString = querystring.stringify(obj);
console.log(queryString); // "name=Sai&age=25"
This is useful when constructing URLs dynamically.
req.on("end", () => {
const parsedBody = querystring.parse(body);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received: ${parsedBody.name}, Age: ${parsedBody.age}`);
});
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Only POST requests are allowed.");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• req.on("data", chunk => { body += chunk; }) collects incoming data.
• querystring.parse(body) converts form data into an object.
28
Full Stack Development (MERN)-CS631PE Department of CSE
Understanding Request, Response, and Server Objects in node js with detail explanation
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• http.createServer() creates an HTTP server.
• res.writeHead(200, { "Content-Type": "text/plain" }) sets the response header.
• res.end() sends the response and closes the connection.
• server.listen(3000) starts the server on port 3000.
29
Full Stack Development (MERN)-CS631PE Department of CSE
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• req.method retrieves the HTTP method (GET, POST, etc.).
• req.url provides the requested URL.
• req.headers contains request headers.
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• url.parse(req.url, true) extracts query parameters.
• parsedUrl.query holds the key-value pairs.
30
Full Stack Development (MERN)-CS631PE Department of CSE
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• res.writeHead(200, { "Content-Type": "application/json" }) sets the response type.
• JSON.stringify(user) converts the object into a JSON string.
req.on("end", () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received Data: ${body}`);
});
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Only POST requests are allowed.");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• req.on("data", chunk => { body += chunk; }) collects incoming data.
• req.on("end", () => { res.end(body); }) sends the processed data back.
31
Full Stack Development (MERN)-CS631PE Department of CSE
Implementing HTTP Clients and Servers in Node.js involves creating a server that listens for
requests and a client that sends requests. Let's break it down step by step.
1. Creating an HTTP Server in Node.js
Node.js provides the built-in http module to create an HTTP server.
Example: Basic HTTP Server
const http = require("http");
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• http.createServer() creates an HTTP server.
• res.writeHead(200, { "Content-Type": "text/plain" }) sets the response header.
• res.end() sends the response and closes the connection.
• server.listen(3000) starts the server on port 3000.
res.on("end", () => {
console.log("Response from server:", data);
});
});
• http.get() sends a GET request to the server.
32
Full Stack Development (MERN)-CS631PE Department of CSE
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• pathname === "/about" serves the About page.
• pathname === "/contact" serves the Contact page.
• Default response serves the Home page.
const options = {
hostname: "localhost",
port: 3000,
path: "/submit",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": data.length
}
33
Full Stack Development (MERN)-CS631PE Department of CSE
};
res.on("end", () => {
console.log("Response from server:", responseData);
});
});
req.write(data);
req.end();
• http.request(options, callback) sends a POST request.
• req.write(data) sends the request body.
• req.end() completes the request.
app.use(express.json());
The OS module in Node.js provides methods to interact with the operating system,
retrieve system information, and manage resources efficiently. Let’s break it down
with detailed explanations and examples.
1. Importing the OS Module
To use the OS module, you need to import it:
const os = require("os");
34
Full Stack Development (MERN)-CS631PE Department of CSE
35
Full Stack Development (MERN)-CS631PE Department of CSE
UNIT-5
Introduction
1. Component-Based Architecture
React encourages the component-based approach, making UI development modular
and scalable.
• Instead of managing entire webpages, React allows breaking down UI into small
reusable components.
• Each component is independent, making debugging and maintenance easier.
Example: Creating a Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Greeting name="Sai" />
Here, Greeting is a reusable component that can be used multiple times.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Only the count updates, preventing unnecessary DOM manipulations.
3. Declarative UI
React’s declarative programming model simplifies UI logic.
36
Full Stack Development (MERN)-CS631PE Department of CSE
• Instead of manually managing UI updates, React describes how UI should look based
on data.
• It automatically updates components when data changes.
Example: Conditional Rendering
function UserStatus({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome, Sai!</p> : <p>Please log in.</p>;
}
React automatically re-renders when isLoggedIn state changes.
function FetchData() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://api.example.com/data")
.then(response => response.json())
.then(result => setData(result));
}, []);
37
Full Stack Development (MERN)-CS631PE Department of CSE
38
Full Stack Development (MERN)-CS631PE Department of CSE
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
Explanation:
• ReactDOM.createRoot(document.getElementById("root")): Attaches React to the
HTML element with id "root".
• <App />: The main component that gets rendered.
The root element exists inside public/index.html:
<div id="root"></div>
React injects the entire app inside this div.
function App() {
return (
<div>
<h1>Welcome to My React App</h1>
<Greeting name="Sai Kishore" /> {/* Using the Greeting component */}
</div>
);
}
function Greeting(props) {
return <h2>Hello, {props.name}!</h2>;
}
39
Full Stack Development (MERN)-CS631PE Department of CSE
The Virtual DOM is a key concept in React that enhances performance by efficiently updating
the UI without directly manipulating the actual Real DOM. Let's break it down step by step.
Re-rendering Entire DOM tree updates Only the changed components update
40
Full Stack Development (MERN)-CS631PE Department of CSE
React compares the new Virtual DOM with the old one using a diffing algorithm.
Step 3: Efficiently Updating the Real DOM
Instead of updating the entire DOM, React replaces only the changed elements, minimizing
performance overhead.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
The Virtual DOM is the backbone of Reacts efficiency, ensuring fast UI updates while
reducing browser workload. This makes React ideal for dynamic applications like
dashboards, social media, and e-commerce sites.
41
Full Stack Development (MERN)-CS631PE Department of CSE
function Greeting() {
return <h1>Hello, Sai Kishore! Welcome to React!</h1>;
}
function App() {
return (
<div>
<Greeting /> {/* Reusing Greeting component */}
</div>
);
}
42
Full Stack Development (MERN)-CS631PE Department of CSE
render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
6. Combining Components
Multiple components can be combined into a larger UI structure.
Example: Nested Components
43
Full Stack Development (MERN)-CS631PE Department of CSE
function Header() {
return <h1>React App</h1>;
}
function Footer() {
return <footer>Copyright © 2025</footer>;
}
function App() {
return (
<div>
<Header />
<p>Main Content</p>
<Footer />
</div>
);
}
function App() {
return <Greeting name="Sai Kishore" />;
}
44
Full Stack Development (MERN)-CS631PE Department of CSE
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
function App() {
return <Profile name="Sai Kishore" age={25} />;
}
45
Full Stack Development (MERN)-CS631PE Department of CSE
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
const [message, setMessage] = useState("");
return (
<div>
<Child updateMessage={setMessage} />
<p>Message: {message}</p>
</div>
);
}
46
Full Stack Development (MERN)-CS631PE Department of CSE
1. Rendering in React
Rendering in React is controlled by ReactDOM and occurs when: ✔ A component is
first mounted (initial render).
A component’s state or props change (re-render).
The parent component updates, affecting child components.
render() {
return <h1>Welcome, {this.props.name}!</h1>;
}
}
47
Full Stack Development (MERN)-CS631PE Department of CSE
Example of componentDidMount()
class DataFetcher extends Component {
constructor(props) {
super(props);
this.state = { data: null };
}
componentDidMount() {
fetch("https://api.example.com/data")
.then(res => res.json())
.then(result => this.setState({ data: result }));
}
render() {
return <p>Data: {JSON.stringify(this.state.data)}</p>;
}
}
componentDidMount() runs after the first render, making it ideal for fetching data.
48
Full Stack Development (MERN)-CS631PE Department of CSE
super(props);
this.state = { count: 0 };
}
componentDidUpdate(prevProps, prevState) {
console.log(`Updated! Previous count: ${prevState.count}`);
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
componentDidUpdate() runs after each state update.
render() {
return <p>Timer running...</p>;
}
}
Used for cleaning event listeners, timers, and subscriptions.
49
Full Stack Development (MERN)-CS631PE Department of CSE
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const interval = setInterval(() => setTime(time + 1), 1000);
function SignupForm() {
const [username, setUsername] = useState("");
return (
<form>
<label>Username:</label>
<input type="text" value={username} onChange={(e) =>
setUsername(e.target.value)} />
<p>Entered: {username}</p>
</form>
);
}
50
Full Stack Development (MERN)-CS631PE Department of CSE
function UserForm() {
const [formData, setFormData] = useState({ name: "", email: "" });
return (
<form>
<input name="name" placeholder="Name" onChange={handleChange} />
<input name="email" type="email" placeholder="Email"
onChange={handleChange} />
<p>Name: {formData.name}, Email: {formData.email}</p>
</form>
);
}
return (
<form onSubmit={handleSubmit}>
51
Full Stack Development (MERN)-CS631PE Department of CSE
return (
<label>
<input type="checkbox" checked={isChecked} onChange={(e) =>
setIsChecked(e.target.checked)} />
Accept Terms & Conditions
</label>
);
}
return (
<form>
<label>
<input type="radio" value="Male" name="gender" onChange={(e) =>
setGender(e.target.value)} />
Male
</label>
<label>
<input type="radio" value="Female" name="gender" onChange={(e) =>
setGender(e.target.value)} />
Female
</label>
<p>Selected Gender: {gender}</p>
52
Full Stack Development (MERN)-CS631PE Department of CSE
</form>
);
}
return (
<select onChange={(e) => setSelectedOption(e.target.value)}>
<option value="">Choose an option</option>
<option value="React">React</option>
<option value="Node.js">Node.js</option>
</select>
);
}
6. Validation in Forms
React allows form validation before submission.
Example: Validating Input
function ValidateForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
return (
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Enter email" onChange={(e) =>
setEmail(e.target.value)} />
<button type="submit">Submit</button>
<p style={{ color: "red" }}>{error}</p>
</form>
53
Full Stack Development (MERN)-CS631PE Department of CSE
);
}
Routing in React
Routing in React allows users to navigate between different views or pages without
reloading the entire application. It is efficiently managed using the React Router library.
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
54
Full Stack Development (MERN)-CS631PE Department of CSE
function Navbar() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} /> {/* Handles unmatched routes */}
</Routes>
55
Full Stack Development (MERN)-CS631PE Department of CSE
function Profile() {
const { username } = useParams();
return <h1>Welcome, {username}!</h1>;
}
56