Middlewares are different types of functions that have access to the req object, res object and the next middleware function in the application’s request-response cycle.
Basically, middlewares are used to handle and modify the req and res object or pass control to the next middleware function according to the conditions.
Example:
In the below example, we are checking through middleware that if the password is equal to 123 then a user can access the home page otherwise not.
index.js
const express = require('express');
const app = express();
// app.use() is used to apply a middleware
app.use(
// A MIDDLEWARE
(req, res, next) => {
let password = req.query.password;
// if password is equal to 123 then call next();
if(password == 123) next();
res.send('Invalid Password. You can't access the home page.');
}
);
app.get('/', (req, res) => {
res.send('Welcome to the Home Page.');
});
app.listen(3000, () => console.log('Your app listening on port 3000'));
Now run the index.js file by running node index command.
Result:
http://localhost:3000/?password=521
http://localhost:3000/?password=123
In the Express JS, there are some types of middleware –
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
Next is – Express JS Cookie
Previous is – Template Engines