SlideShare a Scribd company logo
1 of 17
Download to read offline
Department of Information Technology
2023 – 2024 (ODD SEMESTER)
Year : III IT Course Code : IT2304
Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development
Course code
(as per NBA)
: 21ITC304 Regulation : R2021
UNIT IV
Middleware:
 Middleware functions are the functions that access to the request and response object
(req, res) in request-response cycle.
 A middleware function can perform the following tasks:
o It can execute any code.
o It can make changes to the request and the response objects.
o It can end the request-response cycle.
o It can call the next middleware function in the stack.
Express.js Middleware
Following is a list of possibly used middleware in Express.js app:
 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware
Request Processing:
 Middleware functions are executed in the order they are defined.
 They process the incoming request and can modify the request object, add properties
to it, or perform validations.
Response Handling:
 Middleware functions can also modify the response object (res).
 They can set headers, send a response, or manipulate the response data before it is
sent back to the client.
Chaining Middleware:
 Express allows the chaining of multiple middleware functions.
 Each middleware function in the chain has access to the request and response objects.
The next function is used to pass control to the next middleware in the stack.
Example:
app.use((req, res, next) => {
next(); // Pass control to the next middleware
});
Error Handling:
 Middleware functions can handle errors.
 If an error occurs, the middleware with four parameters (err, req, res, next) is
triggered. This allows for centralized error handling.
Example:
app.use((err, req, res, next) => {
res.status(500).send('Internal Server Error');
});
Authentication and Authorization:
 Middleware is commonly used for authentication and authorization purposes.
 For example, a middleware function can check if a user is authenticated before
allowing access to certain routes.
Example:
const authenticate = (req, res, next) => {
if (userIsAuthenticated) {
next();
} else {
res.status(401).send('Unauthorized');
}
};
app.get('/secured', authenticate, (req, res) => {
res.send('Secured Route');
});
Static File Serving:
 Express provides built-in middleware functions for serving static files.
 This is commonly used to serve CSS, JavaScript, and image files.
Example:
app.use(express.static('public'));
Logging:
 Middleware functions are often used for logging requests, providing valuable insights
into the flow of traffic through the application.
Example:
app.use((req, res, next) => {
console.log(`[${new Date()}] ${req.method} ${req.url}`);
next();
});
Third-Party Middleware:
 Express allows the use of third-party middleware for additional functionality.
 Examples include body parsers for handling request bodies, compression middleware,
and session management middleware.
Example
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Routing:
 In Express.js, routing refers to the process of defining how an application responds to
a client request to a particular endpoint (URL) and HTTP method.
 Express provides a simple and flexible way to handle routing, allowing you to define
routes for different HTTP methods and URL patterns.
Basic Routing:
 A basic example of a route that responds to a GET request at the root URL.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Route Parameters:
 Routes can include parameters, which are specified with a colon : in the route pattern.
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
Handling Different HTTP Methods:
GET Request:
 Responds to a GET request.
app.get('/users', (req, res) => {
// Handle GET request for /users
});
POST Request:
 Responds to a POST request.
app.post('/users', (req, res) => {
// Handle POST request for /users
});
PUT Request:
 Responds to a PUT request.
app.put('/users/:id', (req, res) => {
// Handle PUT request for /users/:id
});
DELETE Request:
 Responds to a DELETE request.
app.delete('/users/:id', (req, res) => {
// Handle DELETE request for /users/:id
});
Middleware in Routing:
Middleware Function:
 Middleware functions can be used in routing to perform tasks before sending a
response.
const middlewareFunction = (req, res, next) => {
// Middleware logic
next();
};
app.get('/users', middlewareFunction, (req, res) => {
// Handle GET request for /users
});
Router Object:
 Express Router objects can be used to create modular and mountable route handlers.
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => {
// Handle GET request for /users
});
module.exports = router;
In your main application file:
const userRoutes = require('./userRoutes');
app.use('/api', userRoutes);
Route Middleware:
Route-Specific Middleware:
 Middleware can be applied to specific routes using the use method.
const authenticationMiddleware = (req, res, next) => {
// Authentication logic
next();
};
app.use('/admin', authenticationMiddleware);
app.get('/admin/dashboard', (req, res) => {
// Handle GET request for /admin/dashboard
});
Express Built-in Middleware:
 Express provides built-in middleware for parsing request bodies, serving static files,
and more.
const express = require('express');
const app = express();
app.use(express.json()); // Parse JSON in request body
app.use(express.static('public')); // Serve static files from the 'public' directory
Session Management:
 In Node.js with Express.js, cookies can be managed using the cookie-parser
middleware.
Install cookie-parser:
 Make sure you have express and cookie-parser installed. If not, you can install them
using npm:
npm install express cookie-parser
Configure cookie-parser in your Express app:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// Use cookie-parser middleware
app.use(cookieParser());
 Adding cookie-parser middleware to your application allows you to easily work with
cookies in your routes.
Setting Cookies:
 You can set cookies using the res.cookie() method. Here's an example:
app.get('/setCookie', (req, res) => {
res.cookie('username', 'exampleUser', { maxAge: 900000, httpOnly: true });
res.send('Cookie set!');
});
 In this example, a cookie named 'username' with the value 'exampleUser' is set. The
maxAge option is set to 900,000 milliseconds (15 minutes), and httpOnly is set to true
for added security.
Reading Cookies:
 You can access cookies through req.cookies. For example:
app.get('/getCookie', (req, res) => {
const username = req.cookies.username || 'No cookie set';
res.send(`Username: ${username}`);
});
 In this example, the value of the 'username' cookie is retrieved from req.cookies.
Clearing Cookies:
 To clear a cookie, you can use the res.clearCookie() method:
app.get('/clearCookie', (req, res) => {
res.clearCookie('username');
res.send('Cookie cleared!');
});
 This example clears the 'username' cookie.
Using Session:
Install express-session:
 Make sure you have express and express-session installed. If not, you can install them
using npm:
npm install express express-session
Configure express-session:
 Set up the express-session middleware in your Express application. This usually
involves requiring it and adding it to the middleware stack. Here's a minimal example:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
secret: A string used to sign the session ID cookie. It should be a random, long, and secure
string.
resave: Forces the session to be saved back to the session store, even if it hasn't been
modified.
saveUninitialized: Forces a session that is "uninitialized" to be saved to the store. A session is
uninitialized when it is new but not modified.
Using Sessions in Routes:
 Once the session middleware is set up, you can use the req.session object to store and
retrieve session data. For example:
app.get('/setSession', (req, res) => {
req.session.username = 'exampleUser';
res.send('Session set!');
});
app.get('/getSession', (req, res) => {
const username = req.session.username || 'No session data';
res.send(`Username: ${username}`);
});
1. Count the number of lines and words using nodejs.
fs module:
 Node.js includes fs module to access physical file system.
 The fs module is responsible for all the asynchronous or synchronous file I/O
operations.
Method Description
fs.readFile(fileName [,options],
callback)
Reads existing file.
fs.writeFile(filename, data[,
options], callback)
Writes to the file. If file exists then overwrite the
content otherwise creates new file.
fs.open(path, flags [,mode],
callback)
Opens file for reading or writing.
fs.appendFile(file, data[,
options], callback)
Appends new content to the existing file.
fs.rename(oldPath, newPath,
callback)
Renames an existing file.
fs.unlink(path, callback); Delete a file.
fs.rmdir(path, callback) Renames an existing directory.
fs.mkdir(path[, mode], callback) Creates a new directory.
fs.readdir(path, callback) Reads the content of the specified directory.
<< Refer your Notes for coding >>
2. Custom Event with Timeout using nodejs.
events module:
 Node.js allows us to create and handle custom events easily by using events
module.
 Event module includes EventEmitter class which can be used to raise and handle
custom events.
EventEmitter Methods Description
emitter.addListener(event, listener) Adds a listener to the end of the listeners array
for the specified event. No checks are made to
see if the listener has already been added.
emitter.on(event, listener) Adds a listener to the end of the listeners array
for the specified event. No checks are made to
see if the listener has already been added. It can
also be called as an alias of
emitter.addListener()
emitter.once(event, listener) Adds a one time listener for the event. This
listener is invoked only the next time the event
is fired, after which it is removed.
emitter.removeListener(event, listener) Removes a listener from the listener array for
the specified event. Caution: changes array
indices in the listener array behind the listener.
emitter.removeAllListeners([event]) Removes all listeners, or those of the specified
event.
emitter.emit(event[, arg1][, arg2][, ...]) Raise the specified events with the supplied
arguments.
const event = require('events'); // importing events module
const e = new event(); // Instantiating the object
// Function to generate the Fibonacci numbers using recurion
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Function to display the Fibonacci numbers with time out
Function fiboDisplay(){
for (let i = 0; i < 10; i++) {
setTimeout(function() {
const fibNumber = fibonacci(i);
console.log(`Fibonacci(${i}) = ${fibNumber}`);
}, i * 2000); // Delay 2 seconds for each number (i * 2000
milliseconds)
}
}
// Binding the event with event listener
e.on("fibo", fiboDisplay)
// Triggering the event
e.emit("fibo")
// Remove the listener
setTimeout(function(){
console.log("Operation cancelled");
e.removeAllListeners("fibo");
}, 10000)
3. HTTP Server
http module:
 Node.js has a built-in module called HTTP, which allows Node.js to transfer data
over the Hyper Text Transfer Protocol (HTTP).
 The HTTP module can create an HTTP server using createServer() that listens to
server ports and gives a response back to the client.
 If the response from the HTTP server is supposed to be displayed as HTML,
include an HTTP header with the correct content type:
Server.js
var httpObj = require('http');
function initM(req, res){
// Set the response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send a response to the client
res.end('Hello, Welcome to NodeJSn');
}
// Create an HTTP server
var server = httpObj.createServer(initM);
// Listen on port 3000
const port = 3000;
server.listen(port, function() {
console.log(`Server is running on http://localhost:${port}`);
});
Client.js
var http = require('http');
// Options for the HTTP request
var options = {
hostname: 'localhost',
port: 3000,
path: '/',
method: 'GET',
};
// Make the HTTP request
var req = http.request(options, function(res){
let data = '';
// Receive data from the response
res.on('data', function(chunk) {
data += chunk;
});
// Handle the end of the response
res.on('end', function() {
console.log(`Response from server: ${data}`);
});
});
// Handle errors
req.on('error', function(error){
console.error(`Request error: ${error.message}`);
});
// Send the request
req.end();
4. URL
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.hostname); //returns 'localhost'
console.log(q.port); //returns '8080'
console.log(q.path); //returns 'default.htm?year=2017&month=february'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'
console.log(qdata);
5. TCP Chat
socket.io module:
 Socket.IO is a library that enables low-latency, bidirectional and event-based
communication between a client and a server.
Server.js
const io = require('socket.io')();
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const port = 3000;
io.on('connection', function(socket) {
console.log('Client connected');
socket.on('disconnect', function(){
console.log('Client disconnected');
});
socket.on('chat message', function(msg){
console.log(`Received: ${msg}`);
rl.question('Enter your response: ', function(response){
socket.emit('chat message', response);
});
});
});
io.listen(port);
console.log(`Server is listening on port ${port}`);
rl.question('Server is ready. Press Enter to start chatting:n', function(){
rl.on('line', function(msg){
io.sockets.emit('chat message', `[Server]: ${msg}`);
rl.prompt();
});
});
Client.js
const io = require('socket.io-client');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const serverUrl = 'http://localhost:3000';
const socket = io(serverUrl);
socket.on('connect', function(){
console.log('Connected to the server');
startChat();
});
socket.on('chat message', function(msg){
console.log(`Received: ${msg}`);
});
socket.on('disconnect', function(){
console.log('Disconnected from the server');
});
function startChat() {
rl.question('Enter your message (or type "exit" to quit): ', function(msg){
if (msg.toLowerCase() === 'exit') {
rl.close();
socket.disconnect();
} else {
socket.emit('chat message', msg);
startChat(); // Continuously prompt for messages
}
});
}

More Related Content

Similar to Full Stack Web Dev Middleware

Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
SenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.ioSenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.ioNils Dehl
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsSebastian Springer
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookiesMahmoudOHassouna
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Lou Sacco
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedureftz 420
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 

Similar to Full Stack Web Dev Middleware (20)

Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Express node js
Express node jsExpress node js
Express node js
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
SenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.ioSenchaTouch 2 and Sencha.io
SenchaTouch 2 and Sencha.io
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Spine.js
Spine.jsSpine.js
Spine.js
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 

More from ArthyR3

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfArthyR3
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfArthyR3
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfArthyR3
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdfArthyR3
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdfArthyR3
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdfArthyR3
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdfArthyR3
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit vArthyR3
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit vArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit iArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)ArthyR3
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography WorkbookArthyR3
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network securityArthyR3
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bankArthyR3
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question keyArthyR3
 

More from ArthyR3 (20)

Unit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdfUnit IV Knowledge and Hybrid Recommendation System.pdf
Unit IV Knowledge and Hybrid Recommendation System.pdf
 
VIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdfVIT336 – Recommender System - Unit 3.pdf
VIT336 – Recommender System - Unit 3.pdf
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
 
Cns
CnsCns
Cns
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

Full Stack Web Dev Middleware

  • 1. Department of Information Technology 2023 – 2024 (ODD SEMESTER) Year : III IT Course Code : IT2304 Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development Course code (as per NBA) : 21ITC304 Regulation : R2021 UNIT IV Middleware:  Middleware functions are the functions that access to the request and response object (req, res) in request-response cycle.  A middleware function can perform the following tasks: o It can execute any code. o It can make changes to the request and the response objects. o It can end the request-response cycle. o It can call the next middleware function in the stack. Express.js Middleware Following is a list of possibly used middleware in Express.js app:  Application-level middleware  Router-level middleware  Error-handling middleware  Built-in middleware  Third-party middleware Request Processing:  Middleware functions are executed in the order they are defined.  They process the incoming request and can modify the request object, add properties to it, or perform validations. Response Handling:
  • 2.  Middleware functions can also modify the response object (res).  They can set headers, send a response, or manipulate the response data before it is sent back to the client. Chaining Middleware:  Express allows the chaining of multiple middleware functions.  Each middleware function in the chain has access to the request and response objects. The next function is used to pass control to the next middleware in the stack. Example: app.use((req, res, next) => { next(); // Pass control to the next middleware }); Error Handling:  Middleware functions can handle errors.  If an error occurs, the middleware with four parameters (err, req, res, next) is triggered. This allows for centralized error handling. Example: app.use((err, req, res, next) => { res.status(500).send('Internal Server Error'); }); Authentication and Authorization:  Middleware is commonly used for authentication and authorization purposes.  For example, a middleware function can check if a user is authenticated before allowing access to certain routes. Example: const authenticate = (req, res, next) => { if (userIsAuthenticated) { next(); } else { res.status(401).send('Unauthorized'); }
  • 3. }; app.get('/secured', authenticate, (req, res) => { res.send('Secured Route'); }); Static File Serving:  Express provides built-in middleware functions for serving static files.  This is commonly used to serve CSS, JavaScript, and image files. Example: app.use(express.static('public')); Logging:  Middleware functions are often used for logging requests, providing valuable insights into the flow of traffic through the application. Example: app.use((req, res, next) => { console.log(`[${new Date()}] ${req.method} ${req.url}`); next(); }); Third-Party Middleware:  Express allows the use of third-party middleware for additional functionality.  Examples include body parsers for handling request bodies, compression middleware, and session management middleware. Example const bodyParser = require('body-parser'); app.use(bodyParser.json()); Routing:  In Express.js, routing refers to the process of defining how an application responds to a client request to a particular endpoint (URL) and HTTP method.
  • 4.  Express provides a simple and flexible way to handle routing, allowing you to define routes for different HTTP methods and URL patterns. Basic Routing:  A basic example of a route that responds to a GET request at the root URL. const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); Route Parameters:  Routes can include parameters, which are specified with a colon : in the route pattern. app.get('/users/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); }); Handling Different HTTP Methods: GET Request:  Responds to a GET request. app.get('/users', (req, res) => { // Handle GET request for /users }); POST Request:  Responds to a POST request. app.post('/users', (req, res) => { // Handle POST request for /users }); PUT Request:  Responds to a PUT request.
  • 5. app.put('/users/:id', (req, res) => { // Handle PUT request for /users/:id }); DELETE Request:  Responds to a DELETE request. app.delete('/users/:id', (req, res) => { // Handle DELETE request for /users/:id }); Middleware in Routing: Middleware Function:  Middleware functions can be used in routing to perform tasks before sending a response. const middlewareFunction = (req, res, next) => { // Middleware logic next(); }; app.get('/users', middlewareFunction, (req, res) => { // Handle GET request for /users }); Router Object:  Express Router objects can be used to create modular and mountable route handlers. const express = require('express'); const router = express.Router(); router.get('/users', (req, res) => { // Handle GET request for /users }); module.exports = router; In your main application file: const userRoutes = require('./userRoutes');
  • 6. app.use('/api', userRoutes); Route Middleware: Route-Specific Middleware:  Middleware can be applied to specific routes using the use method. const authenticationMiddleware = (req, res, next) => { // Authentication logic next(); }; app.use('/admin', authenticationMiddleware); app.get('/admin/dashboard', (req, res) => { // Handle GET request for /admin/dashboard }); Express Built-in Middleware:  Express provides built-in middleware for parsing request bodies, serving static files, and more. const express = require('express'); const app = express(); app.use(express.json()); // Parse JSON in request body app.use(express.static('public')); // Serve static files from the 'public' directory Session Management:  In Node.js with Express.js, cookies can be managed using the cookie-parser middleware. Install cookie-parser:  Make sure you have express and cookie-parser installed. If not, you can install them using npm: npm install express cookie-parser Configure cookie-parser in your Express app: const express = require('express');
  • 7. const cookieParser = require('cookie-parser'); const app = express(); // Use cookie-parser middleware app.use(cookieParser());  Adding cookie-parser middleware to your application allows you to easily work with cookies in your routes. Setting Cookies:  You can set cookies using the res.cookie() method. Here's an example: app.get('/setCookie', (req, res) => { res.cookie('username', 'exampleUser', { maxAge: 900000, httpOnly: true }); res.send('Cookie set!'); });  In this example, a cookie named 'username' with the value 'exampleUser' is set. The maxAge option is set to 900,000 milliseconds (15 minutes), and httpOnly is set to true for added security. Reading Cookies:  You can access cookies through req.cookies. For example: app.get('/getCookie', (req, res) => { const username = req.cookies.username || 'No cookie set'; res.send(`Username: ${username}`); });  In this example, the value of the 'username' cookie is retrieved from req.cookies. Clearing Cookies:  To clear a cookie, you can use the res.clearCookie() method: app.get('/clearCookie', (req, res) => { res.clearCookie('username'); res.send('Cookie cleared!'); });  This example clears the 'username' cookie. Using Session:
  • 8. Install express-session:  Make sure you have express and express-session installed. If not, you can install them using npm: npm install express express-session Configure express-session:  Set up the express-session middleware in your Express application. This usually involves requiring it and adding it to the middleware stack. Here's a minimal example: const express = require('express'); const session = require('express-session'); const app = express(); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true })); secret: A string used to sign the session ID cookie. It should be a random, long, and secure string. resave: Forces the session to be saved back to the session store, even if it hasn't been modified. saveUninitialized: Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified. Using Sessions in Routes:  Once the session middleware is set up, you can use the req.session object to store and retrieve session data. For example: app.get('/setSession', (req, res) => { req.session.username = 'exampleUser'; res.send('Session set!'); }); app.get('/getSession', (req, res) => { const username = req.session.username || 'No session data';
  • 9. res.send(`Username: ${username}`); }); 1. Count the number of lines and words using nodejs. fs module:  Node.js includes fs module to access physical file system.  The fs module is responsible for all the asynchronous or synchronous file I/O operations. Method Description fs.readFile(fileName [,options], callback) Reads existing file. fs.writeFile(filename, data[, options], callback) Writes to the file. If file exists then overwrite the content otherwise creates new file. fs.open(path, flags [,mode], callback) Opens file for reading or writing. fs.appendFile(file, data[, options], callback) Appends new content to the existing file. fs.rename(oldPath, newPath, callback) Renames an existing file. fs.unlink(path, callback); Delete a file. fs.rmdir(path, callback) Renames an existing directory. fs.mkdir(path[, mode], callback) Creates a new directory. fs.readdir(path, callback) Reads the content of the specified directory. << Refer your Notes for coding >> 2. Custom Event with Timeout using nodejs. events module:  Node.js allows us to create and handle custom events easily by using events module.  Event module includes EventEmitter class which can be used to raise and handle custom events. EventEmitter Methods Description emitter.addListener(event, listener) Adds a listener to the end of the listeners array
  • 10. for the specified event. No checks are made to see if the listener has already been added. emitter.on(event, listener) Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. It can also be called as an alias of emitter.addListener() emitter.once(event, listener) Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. emitter.removeListener(event, listener) Removes a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener. emitter.removeAllListeners([event]) Removes all listeners, or those of the specified event. emitter.emit(event[, arg1][, arg2][, ...]) Raise the specified events with the supplied arguments. const event = require('events'); // importing events module const e = new event(); // Instantiating the object // Function to generate the Fibonacci numbers using recurion function fibonacci(n) { if (n <= 1) { return n; } return fibonacci(n - 1) + fibonacci(n - 2); } // Function to display the Fibonacci numbers with time out Function fiboDisplay(){ for (let i = 0; i < 10; i++) { setTimeout(function() { const fibNumber = fibonacci(i);
  • 11. console.log(`Fibonacci(${i}) = ${fibNumber}`); }, i * 2000); // Delay 2 seconds for each number (i * 2000 milliseconds) } } // Binding the event with event listener e.on("fibo", fiboDisplay) // Triggering the event e.emit("fibo") // Remove the listener setTimeout(function(){ console.log("Operation cancelled"); e.removeAllListeners("fibo"); }, 10000) 3. HTTP Server http module:  Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).  The HTTP module can create an HTTP server using createServer() that listens to server ports and gives a response back to the client.
  • 12.  If the response from the HTTP server is supposed to be displayed as HTML, include an HTTP header with the correct content type: Server.js var httpObj = require('http'); function initM(req, res){ // Set the response header res.writeHead(200, { 'Content-Type': 'text/plain' }); // Send a response to the client res.end('Hello, Welcome to NodeJSn'); } // Create an HTTP server var server = httpObj.createServer(initM); // Listen on port 3000 const port = 3000; server.listen(port, function() { console.log(`Server is running on http://localhost:${port}`); }); Client.js var http = require('http'); // Options for the HTTP request var options = {
  • 13. hostname: 'localhost', port: 3000, path: '/', method: 'GET', }; // Make the HTTP request var req = http.request(options, function(res){ let data = ''; // Receive data from the response res.on('data', function(chunk) { data += chunk; }); // Handle the end of the response res.on('end', function() { console.log(`Response from server: ${data}`); }); }); // Handle errors req.on('error', function(error){ console.error(`Request error: ${error.message}`); }); // Send the request
  • 14. req.end(); 4. URL var url = require('url'); var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; var q = url.parse(adr, true); console.log(q.host); //returns 'localhost:8080' console.log(q.hostname); //returns 'localhost' console.log(q.port); //returns '8080' console.log(q.path); //returns 'default.htm?year=2017&month=february' console.log(q.pathname); //returns '/default.htm' console.log(q.search); //returns '?year=2017&month=february' var qdata = q.query; //returns an object: { year: 2017, month: 'february' } console.log(qdata.month); //returns 'february' console.log(qdata); 5. TCP Chat socket.io module:  Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. Server.js const io = require('socket.io')();
  • 15. const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const port = 3000; io.on('connection', function(socket) { console.log('Client connected'); socket.on('disconnect', function(){ console.log('Client disconnected'); }); socket.on('chat message', function(msg){ console.log(`Received: ${msg}`); rl.question('Enter your response: ', function(response){ socket.emit('chat message', response); }); }); }); io.listen(port); console.log(`Server is listening on port ${port}`);
  • 16. rl.question('Server is ready. Press Enter to start chatting:n', function(){ rl.on('line', function(msg){ io.sockets.emit('chat message', `[Server]: ${msg}`); rl.prompt(); }); }); Client.js const io = require('socket.io-client'); const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const serverUrl = 'http://localhost:3000'; const socket = io(serverUrl); socket.on('connect', function(){ console.log('Connected to the server'); startChat(); }); socket.on('chat message', function(msg){
  • 17. console.log(`Received: ${msg}`); }); socket.on('disconnect', function(){ console.log('Disconnected from the server'); }); function startChat() { rl.question('Enter your message (or type "exit" to quit): ', function(msg){ if (msg.toLowerCase() === 'exit') { rl.close(); socket.disconnect(); } else { socket.emit('chat message', msg); startChat(); // Continuously prompt for messages } }); }