AP Lecture 7 Pre-read
What we will learn
1. Optional params in routes
2. Middleware
3. Types of Middleware
a. In-built
b. Third-party
c. Custom
4. Some common middleware
a. express.json()
b. express.urlencoded()
c. express.static()
d. cors
e. morgan
5. Middleware levels
a. App level
b. Router level
c. Route level
6. express.Router()
7. Nodemon
8. Folder Structure
Revision: Express Routes
In Express, routes define how the application responds to client requests.
Basic Syntax
AP Lecture 7 Pre-read 1
app.METHOD(PATH, HANDLER)
METHOD → HTTP method (GET, POST, PUT, DELETE, etc.)
PATH → URL path (string or pattern)
HANDLER → Function executed when the route is matched
Examples
app.get('/', (req, res) => {
res.send('Home Page');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
req.params
Used to capture route parameters defined in the URL.
Parameters are part of the path and are named in the route.
Accessed via req.params .
Example:
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Request: /users/101 → Response: User ID: 101
req.query
Used to capture query string parameters from the URL.
Appears after ? in the URL.
Accessed via req.query .
AP Lecture 7 Pre-read 2
Example:
app.get('/search', (req, res) => {
res.send(`Searching for: ${req.query.q}`);
});
Request: /search?q=books → Response: Searching for: books
Handler Function
A function that executes when a request matches a route.
It receives three arguments: req , res , and optionally next .
Used to send response or call the next middleware.
Example:
app.get('/', (req, res) => {
res.send("Hello World");
});
1. Optional Parameters in Routes
In Express, route parameters can be made optional by adding a ? after the
parameter name.
Example:
app.get('/users/:id?', (req, res) => {
if (req.params.id) {
res.send(`User ID: ${req.params.id}`);
} else {
res.send("No user ID provided");
}
});
Here /users/123 → shows user 123
/users → shows "No user ID provided"
AP Lecture 7 Pre-read 3
2. Middleware
Middleware functions are functions that have access to the request, response,
and the next middleware in the application’s request-response cycle.
Signature:
function middleware(req, res, next) {
// Do something
next(); // Pass to the next middleware/route
}
Middleware can do any of the following:
Execute any code.
Modify req and res .
End the request-response cycle.
Call next() to move to the next function.
3. Types of Middleware
3.1 In-Built Middleware
Express provides some middleware by default:
express.json()
express.urlencoded()
express.static()
3.2 Third-Party Middleware
Installed using npm and imported into the project.
Examples: cors , morgan , helmet , cookie-parser .
3.3 Custom Middleware
User-defined functions written for specific needs.
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
AP Lecture 7 Pre-read 4
next();
}
app.use(logger);
4. Some Common Middleware
4.1 express.json()
Parses incoming JSON requests into req.body .
app.use(express.json());
4.2 express.urlencoded()
Parses URL-encoded data (e.g., from HTML forms).
app.use(express.urlencoded({ extended: true }));
4.3 express.static()
Serves static files (HTML, CSS, JS, images).
app.use(express.static('public'));
4.4 cors
Enables Cross-Origin Resource Sharing.
const cors = require('cors');
app.use(cors());
4.5 morgan
HTTP request logger.
const morgan = require('morgan');
app.use(morgan('dev'));
AP Lecture 7 Pre-read 5
5. Middleware Levels
5.1 App-Level Middleware
Applied on the entire app.
app.use(express.json());
5.2 Router-Level Middleware
Applied to a specific express.Router() .
const router = express.Router();
router.use(middleware);
5.3 Route-Level Middleware
Applied to a specific route.
app.get('/user/:id', middleware, (req, res) => {
res.send("User route");
});
6. express.Router()
Used to create modular and mountable route handlers.
Good for separating routes into different files.
Example:
// userRouter.js
const express = require('express');
const router = express.Router();
router.get('/profile', (req, res) => {
res.send('User Profile');
});
router.get('/all', (req, res) => {
AP Lecture 7 Pre-read 6
res.send('All users');
});
module.exports = router
// server.js
const express = require('express');
const app = express()
const userRouter = require('./userRouter.js')
app.use('/users', router);
app.listen(3000)
The above routes result into:
http://localhost:3000/users/profile
http://localhost:3000/users/all
7. Nodemon
A utility that monitors for changes in files and automatically restarts the
server.
Install:
npm install --save-dev nodemon
Usage in package.json :
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
8. Folder Structure
AP Lecture 7 Pre-read 7
A good folder structure for Express apps:
project/
│── node_modules/
│── public/ # Static files (HTML, CSS, JS, images)
│── src/
│ ├── routes/ # Express route files
│ ├── controllers/ # Route handlers (logic)
│ ├── middlewares/ # Custom middleware
│ ├── models/ # Database models
│ ├── config/ # Config files (db, env, etc.)
│ └── app.js # Express app setup
│── package.json
│── .gitignore
│── README.md
Exercises
Fill in the Blanks
1. The function app.___() is used to handle HTTP GET requests.
2. The function express.___() is used to parse JSON request bodies.
3. Middleware functions must call the ___() function to pass control to the next
handler.
4. To make a route parameter optional, we add a ___ after the parameter
name.
5. The middleware morgan is commonly used for ___ .
Match the Following
Column A Column B
express.json() Serves static files
express.static() Parses JSON data
cors Logs HTTP requests
AP Lecture 7 Pre-read 8
Column A Column B
morgan Enables cross-origin requests
express.urlencoded() Parses form data
AP Lecture 7 Pre-read 9