Middleware

Node.js Express also provides a special routing method, all(), which is not mapped to any HTTP method. But it is used to load Middleware at a path, irrespective of the HTTP method being requested. For example, making HTTP GET and POST requests at http://localhost/middlewareexample will execute the same all() method shown in the following code:

expressApp.all('/middlewareexample', function (req, res) {
    console.log('Accessing the secret1 section ...');
});

Just like in .NET, we have OWIN middleware that can be chained in the request pipeline. In the same way, Node.js Express middleware can also be chained and can be invoked by calling the next middleware with a little change in the function signature. Here is the modified version that takes the next parameter after the response object which provides a handler to the next middleware in the pipeline, defined in a sequence for a particular request path:

expressApp.all('/middlewareexample', function (req, res, next) {
    console.log('Accessing the secret1 section ...');
    next();
});

For example, suppose we have two middlewares and the first middleware just logs the information to the console window, whereas the second returns the HTML content back to the client. Here is the server.js file that contains the two middlewares in the EJS view engine:

//Initialized http object
var http = require('http');
//adding express dependency
var express = require('express');

//creating express application
var expressApp = express();

expressApp.all('/middlewareexample', function (req, res, next) {
    console.log('Middleware executed now calling next middleware in the pipeline');
    next(); // pass control to the next handler
});
expressApp.all('/middlewareexample', function (req, res) {
    res.send("<html><body><div>Middleware executed</div></body></html>");    
});


//declared port
var port = process.env.port || 1337;

//Initialized http server object and use res.write() to send actual response content
var httpServer = http.createServer(expressApp);

//listening for incoming request
httpServer.listen(port);

Now when we access the URL path http://localhost/middlewareexample, the message will be printed on the console and renders the HTML content in the browser:

Middleware

Here is the HTML content that will render in the browser:

Middleware
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.145.193