<!DOCTYPE html>
How to Use Middleware in Express js
Middleware functions are 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 tasks such as authentication, logging, parsing incoming requests, and more.
In Express js, middleware functions are added to the application using the app.use() method. Here’s how you can use middleware in Express js:
1. Creating a Middleware Function
To create a middleware function, simply define a function with three parameters: req, res, and next. For example:
“`javascript
function loggerMiddleware(req, res, next) {
console.log(‘Logging request…’);
next();
}
“`
2. Using Middleware in Your Express Application
To use the middleware function in your Express application, simply add it using the app.use() method before defining your routes. For example:
“`javascript
const express = require(‘express’);
const app = express();
app.use(loggerMiddleware);
app.get(‘/’, (req, res) => {
res.send(‘Hello World!’);
});
app.listen(3000, () => {
console.log(‘Server is running on http://localhost:3000’);
});
“`
3. Using Multiple Middleware Functions
You can use multiple middleware functions in your Express application by passing them as arguments to the app.use() method. For example:
“`javascript
app.use(loggerMiddleware);
app.use(authMiddleware);
“`
4. Error Handling Middleware
You can also create error handling middleware functions in Express js. Error handling middleware functions have four parameters (err, req, res, next) and are defined with an extra error parameter. For example:
“`javascript
function errorHandlerMiddleware(err, req, res, next) {
console.error(err);
res.status(500).send(‘Internal Server Error’);
}
“`
Remember to place error handling middleware functions at the end of your middleware chain to catch any errors that occur in your application.
Using middleware in Express js allows you to separate concerns in your application and perform common tasks across your routes. By following these steps, you can effectively use middleware in Express js to enhance the functionality of your application.
I love u vids man like seriously