Creating Custom Middleware

With Express, you can create your own middleware. All you need to do is provide a function that accepts the Request object as the first parameter, the Response object as the second parameter, and next as the third parameter. The next parameter is a function passed by the middleware framework that points to the next middleware function to execute, so you must call next() prior to exiting your custom function, or the handler will never be called.

To illustrate how easy it is to implement your own custom middleware functionality in Express, Listing 19.10 implements a middleware function named queryRemover() that strips the query string off the URL before sending it on to the handler.

Notice that queryRemover() accepts the Request and Response objects as the first two parameters and next as the third parameter. The next() callback function is executed prior to leaving the middleware function, as required. Figure 19.6 displays the console output; as you can see, the query string portion of the URL has been removed.

Listing 19.10 express_middleware.js: Implementing custom middleware to remove the query string from the Request object


01 var express = require('express'),
02 var app = express();
03 function queryRemover(req, res, next){
04   console.log(" Before URL: ");
05   console.log(req.url);
06   req.url = req.url.split('?')[0];
07   console.log(" After URL: ");
08   console.log(req.url);
09   next();
10 };
11 app.use(queryRemover);
12 app.get('/no/query', function(req, res) {
13   res.send("test");
14 });
15 app.listen(80);


Image

Figure 19.6 Implementing custom middleware to remove the query string from the Request object.

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

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