This document discusses middleware in Express.js web application frameworks. It defines middleware as functions that have access to the request and response objects and can perform tasks like executing code, modifying requests and responses, ending the request-response cycle, or calling the next middleware function. The document then provides examples of different types of middleware like application-level middleware, router-level middleware, error-handling middleware, and built-in middleware from Express. It explains how middleware can be used for tasks like request processing, response handling, authentication, authorization, static file serving, logging, and routing. It also covers using middleware with routes, cookies, sessions, and other concepts in Express.
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')();