Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

node.js - conditionally use a middleware depending on request parameter express

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

question from:https://stackoverflow.com/questions/21271492/conditionally-use-a-middleware-depending-on-request-parameter-express

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...