I am trying to decide on a middleware to use based on request query parameter.
in the main module I have something like this:
app.use(function(req, res){ if (req.query.something) { // pass req, res to middleware_a } else { // pass req, res to middleware_b } });
middleware_a
and middleware_b
are both express apps themselves created by express()
function and not regular middleware functions (function(req, res, next)
)
can't find a way to do it
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle.
We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.
To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.
Middleware functions are an integral part of an application built with the Express framework (henceforth referred to as Express application). They access the HTTP request and response objects and can either terminate the HTTP request or forward it for further processing to another middleware function.
There is nothing magical about connect/express 'middleware': they are just functions - and you can call them as you would call any other function.
So in your example:
app.use(function(req, res, next){ if (req.query.something) { middlewareA(req, res, next); } else { middlewareB(req, res, next); } });
That said, there might be more elegant ways of constructing hierarchical express applications. Check out TJ's video
I know this issue is old, but I would like to share my solution. I solved this by making a function that returned a Middleware with a callback.
Example middleware:
function isAdminUser(callback){ return function(req, res, next){ var userId = callback(req); // do something with the userID next(); } }
Then you can do the following in the express router object
app.use(isAdminUser(function(req){ return req.body.userId });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With