SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler 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
}
});
}

Mais conteúdo relacionado

Mais procurados

Sistem ketatanegaraan republik indonesiastruktur pemerintahan indonesia
Sistem ketatanegaraan republik indonesiastruktur pemerintahan indonesiaSistem ketatanegaraan republik indonesiastruktur pemerintahan indonesia
Sistem ketatanegaraan republik indonesiastruktur pemerintahan indonesia
nurul khaiva
 
Penyandang disabilitas
Penyandang disabilitasPenyandang disabilitas
Penyandang disabilitas
Den Hendar
 
Dinamika pelaksanaan undang – undang dasar 1945
Dinamika pelaksanaan undang – undang dasar 1945 Dinamika pelaksanaan undang – undang dasar 1945
Dinamika pelaksanaan undang – undang dasar 1945
Lela Warni
 

Mais procurados (20)

Politik Hukum - Pertemuan Keempat - 4. politik hukum amandemen uud 1945
Politik Hukum - Pertemuan Keempat - 4. politik hukum amandemen uud 1945Politik Hukum - Pertemuan Keempat - 4. politik hukum amandemen uud 1945
Politik Hukum - Pertemuan Keempat - 4. politik hukum amandemen uud 1945
 
Makalah pemberdayaan masyarakat desa
Makalah pemberdayaan masyarakat desaMakalah pemberdayaan masyarakat desa
Makalah pemberdayaan masyarakat desa
 
Pembentukan Sikap dan Tingkah Laku
Pembentukan Sikap dan Tingkah LakuPembentukan Sikap dan Tingkah Laku
Pembentukan Sikap dan Tingkah Laku
 
Health belief model
Health belief modelHealth belief model
Health belief model
 
Sistem ketatanegaraan republik indonesiastruktur pemerintahan indonesia
Sistem ketatanegaraan republik indonesiastruktur pemerintahan indonesiaSistem ketatanegaraan republik indonesiastruktur pemerintahan indonesia
Sistem ketatanegaraan republik indonesiastruktur pemerintahan indonesia
 
Model Formulasi Kebijakan
Model Formulasi KebijakanModel Formulasi Kebijakan
Model Formulasi Kebijakan
 
Penyandang disabilitas
Penyandang disabilitasPenyandang disabilitas
Penyandang disabilitas
 
Trial dan error 2
Trial dan error 2Trial dan error 2
Trial dan error 2
 
Askes sosial dan komersil
Askes sosial dan komersilAskes sosial dan komersil
Askes sosial dan komersil
 
Organisasi Pemerintahan
Organisasi PemerintahanOrganisasi Pemerintahan
Organisasi Pemerintahan
 
Teori politik
Teori politikTeori politik
Teori politik
 
Urgensi pendidikan karakter
Urgensi pendidikan karakterUrgensi pendidikan karakter
Urgensi pendidikan karakter
 
Data penelitian
Data penelitianData penelitian
Data penelitian
 
Teori Abraham Maslow
Teori Abraham Maslow Teori Abraham Maslow
Teori Abraham Maslow
 
konseptualisasi penelitian
konseptualisasi penelitiankonseptualisasi penelitian
konseptualisasi penelitian
 
Advokasi Kesehatan
Advokasi KesehatanAdvokasi Kesehatan
Advokasi Kesehatan
 
Modul 1 konsep dan studi kebijakan publik
Modul 1 konsep dan studi kebijakan publikModul 1 konsep dan studi kebijakan publik
Modul 1 konsep dan studi kebijakan publik
 
Sistem Penyelenggaraan Pemerintahan NKRI
Sistem Penyelenggaraan Pemerintahan NKRISistem Penyelenggaraan Pemerintahan NKRI
Sistem Penyelenggaraan Pemerintahan NKRI
 
Dinamika pelaksanaan undang – undang dasar 1945
Dinamika pelaksanaan undang – undang dasar 1945 Dinamika pelaksanaan undang – undang dasar 1945
Dinamika pelaksanaan undang – undang dasar 1945
 
Pengertian Advokasi
Pengertian AdvokasiPengertian Advokasi
Pengertian Advokasi
 

Semelhante a NodeJS and ExpressJS.pdf

node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
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.ppt
WalaSidhom1
 

Semelhante a NodeJS and ExpressJS.pdf (20)

Express JS
Express JSExpress JS
Express JS
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
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
 

Mais de ArthyR3

Mais de 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
 

Último

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 

Último (20)

Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
The Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptxThe Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptx
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024
 
How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 

NodeJS and ExpressJS.pdf

  • 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 } }); }