Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining multiple pieces of middleware for specific route in ExpressJS

I want to just verify something but have't been able to find anything in the Express docs or online regarding this (although I know it's a feature).

I could just test this out but I don't really have a nice template and would like to hear from the community.

If I define a route in express like such:

app.get('/', function (req, res) {   res.send('GET request to homepage'); }); 

I can also define a middleware and load it directly, such as

middleware = function(req, res){   res.send('GET request to homepage'); });  app.get('/', middleware) 

However, I can also chain at least one of these routes to run extra middleware, such as authentication, as such:

app.get('/', middleware, function (req, res) {   res.send('GET request to homepage'); }); 

Are these infinitely chainable? Could I stick 10 middleware functions on a given route if I wanted to? I want to see the parameters that app.get can accept but like mentioned I can't find it in the docs.

like image 913
Anthony Avatar asked Aug 10 '15 20:08

Anthony


People also ask

How many middleware can be on a single route?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.

Which component can be used to route multiple data over a single line?

Multiplexer means many into one. A multiplexer is a circuit used to select and route any one of the several input signals to a single output. A simple example of an non-electronic circuit of a multiplexer is a single pole multi-position switch.

How can we create Chainable route handlers for a route path in Expressjs app?

By using app. route() method, we can create chainable route handlers for a route path in Express.

How do I use middleware on my Express router?

Adding a Middleware Function to All Requests For applying the middleware function to all routes, we will attach the function to the app object that represents the express() function. Since we have attached this function to the app object, it will get called for every call to the express application.


1 Answers

Consider following example:

const middleware = {     requireAuthentication: function(req, res, next) {         console.log('private route list!');         next();     },     logger: function(req, res, next) {        console.log('Original request hit : '+req.originalUrl);        next();     } } 

Now you can add multiple middleware using the following code:

app.get('/', [middleware.requireAuthentication, middleware.logger], function(req, res) {     res.send('Hello!'); }); 

So, from the above piece of code, you can see that requireAuthentication and logger are two different middlewares added.

like image 181
Ankur Soni Avatar answered Sep 23 '22 20:09

Ankur Soni