0% found this document useful (0 votes)
29 views24 pages

Express.js Middleware and Routing Guide

Middleware in Express.js is essential for managing tasks during the request-response cycle, allowing functions to access request and response objects and control the flow of the application. There are various types of middleware, including application-level, router-level, error-handling, built-in, third-party, method-specific, and multiple callback middleware. Routing in Express.js defines how the application responds to client requests, utilizing HTTP methods and URL patterns, with features such as route parameters, query parameters, and middleware chains.

Uploaded by

heramb.chaudhri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views24 pages

Express.js Middleware and Routing Guide

Middleware in Express.js is essential for managing tasks during the request-response cycle, allowing functions to access request and response objects and control the flow of the application. There are various types of middleware, including application-level, router-level, error-handling, built-in, third-party, method-specific, and multiple callback middleware. Routing in Express.js defines how the application responds to client requests, utilizing HTTP methods and URL patterns, with features such as route parameters, query parameters, and middleware chains.

Uploaded by

heramb.chaudhri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Middleware and routing

Middleware

Middleware in [Link] plays a crucial role in handling tasks during the request-
response cycle.

It consists of functions that have access to the request object (req), the response
object (res), and the next middleware function in the application’s request-response
cycle

Middleware functions can perform various tasks, such as modifying request and
response objects, terminating the request-response cycle, and calling the next
middleware function.
Middleware Function

Middleware functions are the functions that access to the request and response object
(req, res) in request-response cycle.

Middleware function can perform following task:

1. It can execute the any code


2. It can make changes to the request and the response objects.
3. It can end the request-response cycle.
4. It can call the next middleware function in the stack.
Types of Middleware
[Link]-level Middleware [Link]((req, res, next)
=> {
[Link]('This is
● This middleware is executed for
every incoming request to the
an application-level
application. middleware');
● It logs a message to the console next();
and then calls the next() function to
});
pass control to the next middleware
in the stack.
Types of Middleware
[Link]-level Middleware const router =
[Link]();

● Similar to application-level [Link]((req, res,


middleware, but it's applied to a
specific router. In this example, it next) => {
logs a message for every request to [Link]('This is a
the router. router-level
middleware');
next();
});
Types of Middleware
3. Error-handling Middleware [Link]((err, req, res,
next) => {

● This middleware has four [Link]([Link])


parameters, with the first one (err)
representing an error. ;
● It's executed when an error occurs
during the request-response cycle. It [Link](500).send('So
logs the error and sends an error
mething went wrong!');
response.
});
Types of Middleware
4. Built-in Middleware [Link]([Link]());
[Link]([Link]
ed({ extended: true }));
● Express provides built-in [Link]([Link]('
middleware functions for common
tasks. The examples above public'));
demonstrate JSON and form data
parsing, as well as serving static
files.
Types of Middleware
5. Third-party Middleware const bodyParser =
require('body-parser');
const helmet =
● Third-party middleware modules like require('helmet');
body-parser, helmet, and morgan
enhance Express functionality. const morgan =
● They are added to the application require('morgan');
using [Link]().
[Link]([Link]());
[Link](helmet());
[Link](morgan('combined'));
Types of Middleware
6. Method-specific
Middleware
[Link]('/route', (req, res,
next) => {
[Link]('This
● Middleware can be applied to middleware is specific to
specific HTTP methods and routes.
In this example, the middleware is the GET method for /route');
executed only for GET requests to next();
the '/route' path });
Types of Middleware
7. Multiple Callback
Middleware
[Link]('/route',
middleware1, middleware2,
(req, res) => {
● Multiple middleware functions can // Route handler
be chained together. In this
example, middleware1 and [Link]('Response from
middleware2 are executed the route handler');
sequentially before reaching the });
route handler
Routing

Routing in [Link] refers to the process of defining how an application responds to client
requests to specific endpoints or URLs

In Express, routing is a way to map HTTP methods (such as GET, POST, PUT, DELETE) and
URL patterns to specific pieces of code that handle those requests. The core building block for
routing in Express is the app object, which represents the Express application.
Key Concept and Features of Routing in [Link]

Basic Route Handling


[Link]('/', (req, res) => {
[Link]('Hello, World!');
});

Define routes using HTTP [Link]('/submit', (req, res)


=> {
methods (GET, POST, PUT, // Handle POST request to
DELETE) and corresponding /submit
URL patterns. });
Key Concept and Features of Routing in [Link]

Route Parameters
[Link]('/users/:userId', (req,
res) => {
const userId =
Capture values from the URL [Link];
[Link](`User ID: $
using parameters {userId}`);
});
Key Concept and Features of Routing in [Link]

Query Parameters

[Link]('/search', (req, res)


=> {
const query = [Link].q;
Access query parameters [Link](`Search Query: $
from the URL {query}`);
});
Key Concept and Features of Routing in [Link]

Route Middleware const middlewareFunction =


(req, res, next) => {
// Middleware logic
next();
};
Apply middleware functions to
[Link]('/protected',
specific routes or globally middlewareFunction, (req, res)
using [Link]() => {
[Link]('Protected Route');
});
Key Concept and Features of Routing in [Link]

Router Objects
const router =
[Link]();

[Link]('/', (req, res) => {


Organize routes into modular // Handle GET request to /
});
routers using [Link]()
[Link]('/api', router); //
Mount the router at /api
Key Concept and Features of Routing in [Link]
Route Handlers and [Link](
'/example',
Middleware Chains
(req, res, next) => {
// First middleware
next();
},
Chain multiple route handlers (req, res) => {
or middleware functions for a // Second middleware or
route handler
single route.
[Link]('Example Route');
}
);
Key Concept and Features of Routing in [Link]
// routes/[Link]
Express Router Module const express = require('express');
const router = [Link]();

[Link]('/:userId', (req, res) =>


{
Use the Express Router // Handle GET request to
module for more complex /user/:userId
applications to separate });
[Link] = router;
concerns and organize routes.
// [Link]
const userRouter =
require('./routes/user');
[Link]('/user', userRouter);
Understand
What is the purpose of middleware in [Link]?
a. To define routes
b. To handle client requests
c. To serve static files
d. To organize database queries B
Apply
When using [Link](), how is the control passed to the next middleware?
a. By calling next()
b. By calling continue()
c. Automatically
d. By returning a value A
Apply
How can you organize routes into modular routers in [Link]?
a. Using [Link]()
b. Using [Link]()
c. By creating separate Express applications
d. By using only [Link]() and [Link]() B
Understand
In [Link], what does the next function do in the context of
middleware?
a. It ends the request-response cycle
b. It passes control to the next middleware in the stack
c. It sends a response to the client
d. It defines a new route
B
Thank You

You might also like