Node.js - Middleware - Day Ten

Middleware functions are functions that have the access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named "next". If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Middleware functions can perform the following tasks.
  • End the Request Response Cycle
  • Execute any code
  • Make changes to Request-Response Cycle
  • Call next Middleware function.

Let’s take a simple example of middleware function.

Example

  1. var express = require('express');  
  2. var app = express();  
  3. var fun1 = function (req, res, next) {  
  4. console.log("This is Fun1 Middleare funcion");  
  5. next();  
  6. };  
  7. var fun2 = function (req, res, next) {  
  8. console.log("This is Fun2 Middleare funcion");  
  9. next();  
  10. };  
  11.   
  12. app.use('/', fun1);  
  13. app.use('/', fun2);  
  14.   
  15. app.get('/'function (req, res) {  
  16. res.send("Hello! World");  
  17. })  
  18.   
  19. app.listen(1400);  
Output



In this example. we have created two middleware functions that execute or run before the response is sent to the client. Each middleware function contains three parameters. First parameter denotes the request object, second parameter denotes the response object, and the last parameter denotes the next middleware function.

Order of the execution of middleware function will be similar to the order in which they are used or included in file.

Change in Request or Response Objects

As I said, the middleware function can be used to change the request or response object. Let’s take an example.

Example
  1. var express = require('express');  
  2. var app = express();  
  3. var fun1 = function (req, res, next) {  
  4. console.log("This is Fun1 Middleare funcion");  
  5. req.requestTime = Date.now()  
  6. next();  
  7. };  
  8. app.use('/', fun1);  
  9. app.get('/'function (req, res) {  
  10. res.send("<h2>Requested At: "+ req.requestTime+"</h2>");  
  11. })  
  12.   
  13. app.listen(1400);  
Output



In this example, we have created a middleware function that takes the request object and attaches the requestTime property to request object.

Types of Middleware function

Express supports five types of middleware functions.
  • Application Level Middleware function
  • Router Level Middleware function
  • Exception Handling Middleware function
  • Built-In Middleware function
  • Third-Party Middleware function

Application Middleware Function

In application level middleware functions, functions are bound to an instance of the app object, by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as, GET, PUT, or POST) in lowercase.

Example

  1. var express = require('express');  
  2. var app = express();  
  3. var fun1 = function (req, res, next) {  
  4. console.log("This is Fun1 Middleare funcion");  
  5. next();  
  6. };  
  7. var fun2 = function (req, res, next) {  
  8. console.log("This is Fun2 Middleare funcion");  
  9. next();  
  10. };  
  11. var fun3 = function (req, res, next) {  
  12. res.send("Hello! World")  
  13. };  
  14.   
  15. app.use('/', fun1);  
  16. app.use('/', fun2);  
  17. app.use('/', fun3);  
  18.   
  19. app.listen(1400);  
Output




Router Level Middleware

Router level middleware function works in a similar way to application level middleware, except it binds to the express.Router() object.

Example

Create a router.js file and add the following code into that file.
  1. var express = require('express')  
  2. var routes = express.Router();  
  3.   
  4. //Middleware function  
  5. var fun1 = function (req, res, next) {  
  6. console.log("This is Fun1 Middleare funcion");  
  7. next();  
  8. };  
  9. var fun2 = function (req, res, next) {  
  10. console.log("This is Fun2 Middleare funcion");  
  11. next();  
  12. };  
  13.   
  14. routes.use('/', fun1);  
  15. routes.use('/', fun2);  
  16. //routing  
  17. routes.get('/'function (req, res) {  
  18. res.send("<html><head></head><body><h1>This is demo App</h1></body></html>");  
  19. });  
  20.   
  21. routes.get('/:id'function (req, res) {  
  22. res.send("Your Id is: " + req.params.id);  
  23. });  
  24.   
  25. routes.get('/api/:name'function (req, res) {  
  26. res.send("Your Id is: " + req.params.name);  
  27. });  
  28. routes.get('/:name/:id'function (req, res) {  
  29. res.send("Your Id is: " + req.params.id + " and Your Name is : " + req.params.name);  
  30. });  
  31.   
  32. routes.get('*'function (req, res) {  
  33. res.send("Sorry! URL not found");  
  34. });  
  35.   
  36. module.exports = routes;  
In the above code, we have defined the routing for the application.

Index.js
  1. var express_Obj = require('express')  
  2. var express = express_Obj();  
  3. var routes = require('./router.js');  
  4.   
  5. //Use Router as Middleware  
  6.   
  7. express.use('/', routes);  
  8. //listener  
  9. express.listen(1400);  
Output









Exception Middleware Function

Error handling in Express is done by this kind of middleware. The Error Handling Middleware function takes four parameters. The first parameter defines the error object, the second parameter denotes to the request object, the third parameter denotes to the response object, and the last parameter denotes to the next middleware function.

Example
  1. var express = require('express');  
  2. var app = express();  
  3.   
  4. app.get('/'function (req, res) {  
  5. //Create an error and pass it to the next function  
  6. var err = new Error("Something going wrong");  
  7. next(err);  
  8. });  
  9.   
  10. app.use(function (err, req, res, next) {  
  11. res.status(500);  
  12. res.send("<h2>OOPS, something going wrong.</h2>")  
  13. });  
  14.   
  15. app.listen(1400);  
Output



Built In Middleware Functions

The only built-in middleware function in Express is express.static. This function is based on serve-static, and is responsible for serving static assets such as HTML files, images, and so on.

First create Index.html page and insert the below code in this file.

Index.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.  <link rel="stylesheet" href="midStyle.css" />  
  5. </head>  
  6. <body>  
  7.   
  8.     <table>  
  9.         <tr>  
  10.             <th>Company</th>  
  11.             <th>Contact</th>  
  12.             <th>Country</th>  
  13.         </tr>  
  14.         <tr>  
  15.             <td>Pankaj</td>  
  16.             <td>1234567890</td>  
  17.             <td>India</td>  
  18.         </tr>  
  19.         <tr>  
  20.             <td>Rahul</td>  
  21.             <td>2345678910</td>  
  22.             <td>Mexico</td>  
  23.         </tr>  
  24.         <tr>  
  25.             <td>Sandeep</td>  
  26.             <td>6541230789</td>  
  27.             <td>Austria</td>  
  28.         </tr>  
  29.         <tr>  
  30.             <td>Sanjeev</td>  
  31.             <td>231459870</td>  
  32.             <td>UK</td>  
  33.         </tr>  
  34.   
  35.     </table>  
  36.   
  37. </body>  
  38. </html>   
In Index.html file, we define the html page that we will send to the client. Create a “midstyle.css” file and copy this code into the file. This file contains CSS properties for our html page.
  1. table {  
  2.             font-family: arial, sans-serif;  
  3.             border-collapse: collapse;  
  4.             width: 100%;  
  5.         }  
  6.   
  7.         td, th {  
  8.             border: 1px solid #dddddd;  
  9.             text-align: left;  
  10.             padding: 8px;  
  11.         }  
  12.   
  13.         tr:nth-child(even) {  
  14.             background-color: #dddddd;  
  15.         }  
Index.js
  1. var express = require('express');  
  2. var fs = require('fs');  
  3. var app = express();  
  4.   
  5. app.get('/'function (req, res) {  
  6.   
  7. res.writeHead(200, { 'Content-Type''text/html' });  
  8. fs.readFile(__dirname + '/index.html'function (err, data) {  
  9. res.end(data.toString());  
  10. })  
  11. });    
  12.   
  13. app.listen(1400);  
In the above code, we read the data from “index.html” file and send this data as response to client. Then, define the content-type of data to “text/html” that means, the data retrieved as response is HTML type.

Now, run the application in your browser. When you run this application, you will get the below output.



You can see that we get table formatted data that we send as read from the “index.html” page, but it doesn’t contain the style properties that we defined. So, what is going wrong? Let’s check the issue. Now, right click on page and click on “Inspect Element”. In Network section, you will find that for “midStyle.css”, we are getting “404 Not Found” error.



Now, the question arises, why do we get “404 Not Found” Error for “midStyle.css” file? The reason for this is that we get two requests at the server - one for server and another for “midStyle.css”. “midStyle.css” is a static file and we don’t define any middleware function that can handle this request and send(bind) the static files to the response.
 
Express defines an “express.static” in-built middleware function that handles such types of requests. Let’s modify our code and view the effects. Now, add “app.use('/', express.static(__dirname));” line of code in your application.



When you save this and run the application, you will get the below output.



You can see that now we get the “200 Ok” status code for “midStyle.css” request. “Express.static” middleware function is used to handle the request for static files, like CSS, JavaScript, images.

Third Party Middleware

Third party middleware functions are used to enhance the functionality of Express. Express uses several types of third party middleware functions like “Body-Parser”, “Cookies_Parser”, “Express-Session”. We will read about these middleware functions in the next articles.

You can get more about third-party middleware here.



Conclusion

In this article, we took a brief introduction about middleware function and how Express handles the request for static files. In the next article, we will cover some more topics of Node.js.


Similar Articles