A middleware is a way of enclosing functionality,that operates on a HTTP to your application.In practice,it actually takes three arguments:a request object,response object and a next function.
Sometimes it might contain four arguments,the fourth argument being a err object.
Let's write an example of a middleware and use it to understand the concept of middlewares.
app.use(function(req,res,next){
console.log('This is a simple middleware.");
next();
});
The middleware example above uses a different route handler(often called app.VERB).As you have noticed,it does not specify a path.You can add the /* path as a first parameter but this is option,since if omitted,it will still match on all paths.
The request and response objects are self-explanatory.My main concern is the next function.
Middleware in express is a matter of where they are put in the main app.js file.So what this middleware basically does is display a message,and then the next function heads over to the next route handler below this middleware.Middleware is executed in what is called a pipeline;basically following an order.
The immediate route handler following this middleware will be executed after the middleware is executed.
Let's create an error 404 middleware which will be executed incase the user visits a page that does not exist.
//custom 404 page
app.use(function(req,res,next){
res.type("text/plain");
res.status(404);
res.send("Error : Page not found.");
});
This middleware will be put below all other routes.Incase the route being sought by the user is not found,the app will head over to this middleware and implement it.
Let's experiment with the most used middleware; body-parser middleware.It is used to parse the URL-encoded body.Let's say we have a form and want to capture what the user has put.The body-parser middleware avails the req.body object so as to access the form fields.We shall create a form now.
<!--form example-->
<form method="POST" action="process">
<label for="fieldName">Full Name:</label>
<input name="fullName" type="text">
<label for="fieldPassword">Password:</label>
<input name="password" type="password">
</form>
We install the body-parser middleware now
npm install --save body-parser
Our form is ready,now create a route handler for this form.
//we link the middleware to avail the req.body
app.use(require("body-parser")());
//get user input and display it
app.post("/process",(req,res)=>{
const name = req.body.name;
const password = req.body.password;
console.log(name);
console.log(password);
});
And that's all there is.
Note: With the latest Express version,body-parser is available even without installing it separately.Check out all about it here
Next,I will talk about persistence in express using mongodb and the object document mapper(ODM) ,mongoose.
Stay tuned. adios!
Top comments (2)
cool stuff
thanks @antinomaino