Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Consider following example:

var 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 above piece of code, you can see that "requireAuthentication" and "logger" are two different middlewares added.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...