【问题标题】:Understanding middleware and route handler in Express.js了解 Express.js 中的中间件和路由处理程序
【发布时间】:2016-06-11 02:48:49
【问题描述】:

我正在尝试了解中间件和路由处理程序在 Express 中的工作方式。在Web Development with Node and Express,作者给出了一个有趣的路由和中间件的例子,但没有给出实际的细节。

请有人帮助我理解以下示例中每个步骤发生的情况,以便我确定自己的想法正确吗?这是示例(以我的理解和cmets中的问题):

//get the express module as app
var app = require('express')();

//1. when this module is called, this is printed to the console, always.
app.use(function(req, res, next){ 
  console.log('\n\nALLWAYS');
  next();
});

//2. when a route /a is called, a response 'a' is sent and the app stops. There is no action from here on
app.get('/a', function(req, res){ console.log('/a: route terminated'); res.send('a');
});

//3. this never gets called as a consequence from above
app.get('/a', function(req, res){
            console.log('/a: never called');
});

//4. this will be executed when GET on route /b is called
//it prints the message to the console and moves on to the next function
//question: does this execute even though route /a (2) terminates abruptly?
app.get('/b', function(req, res, next){
            console.log('/b: route not terminated');
next();
});

//5. question: this gets called after above (4)?
app.use(function(req, res, next){ 
  console.log('SOMETIMES');
  next();
});

//6. question: when does this get executed? There is already a function to handle when GET on /b is called (4)
app.get('/b', function(req, res, next){
  console.log('/b (part 2): error thrown' );
  throw new Error('b failed');
});

//7. question: I am not sure when this gets called... ?
app.use('/b', function(err, req, res, next){
  console.log('/b error detected and passed on');
  next(err);
});

//8. this is executed when a GET request is made on route /c. It logs to the console; throws an error.
app.get('/c', function(err, req){
  console.log('/c: error thrown');
  throw new Error('c failed');
});

//9. question: this catches the above error and just moves along?
app.use('/c', function(err, req, res, next) {
  console.log('/c: error deteccted but not passed on');
  next();
});

//10. question: this follows the above and prints an error based on above?
//This also sends a 500 reponse?
app.use(function(err, req, res, next){
  console.log('unhandled error detected: ' + err.message);
  res.send('500 - server error');
});

//11. question: this is the catch all for something that falls through and sends a 404?
app.use(function(req, res){
  console.log('route not handled');
  res.send('404 - not found');
});

//12. This app listens on the 3000 port.
app.listen(3000, function(){
            console.log('listening on 3000');
});

【问题讨论】:

  • 您需要比这更具体。 究竟你不明白什么?
  • 在代码中添加了我的理解和问题。
  • 这就像试图一口气吃掉整个披萨。首先切成片(app.get 是做什么的?app.use 是做什么的?next 是什么?等等),然后对每一片进行小口切片(这意味着什么 2 个 app.get 调用使用相同的路径?)
  • 您有时间阅读我的回答吗?

标签: javascript node.js express web middleware


【解决方案1】:

您应该查看 Express 文档。它充满了您会发现有用的资源,特别是如果您是 Express 的新手。以下是有关您的问题的文档相关部分的一些链接。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    在 express 中,注册序列中间件有很大的不同,当 express 收到请求时,它只是执行注册的中间件,并且与请求的 url 匹配。

    express 中间件具有以下签名

    function(req,res,next){}

    req: request object.
    res: response object.
    next: next middleware thunk.
    

    特殊的错误处理中间件

    function(err, req,res,next){}

    err: error that was caught
    req: request object.
    res: response object.
    next: next middleware thunk.
    

    我正在更新代码本身中的 cmets

        //get the express module as app
        var app = require('express')();
    
        //1. when this *middleware* is called, this is printed to the console, always.
        //As this is first registered middleware, it gets executed no matter what because no url match were provided. This middleware does not stop the middleware chain execution as it calls next() and executes next middleware in chain.
    
        app.use(function(req, res, next){ 
          console.log('\n\nALLWAYS');
          next();
        });
    
        //2. when a route /a is called, a response 'a' is sent and 
        //the app stops. There is no action from here on
        //chain stops because this middleware does not call next()
        app.get('/a', function(req, res, next){ 
             console.log('/a: route terminated'); 
             res.send('a');
        });
    
        //3. this never gets called as a consequence from above
        //because (2) never calls next.
        app.get('/a', function(req, res){
                    console.log('/a: never called');
        });
    
        //4. this will be executed when GET on route /b is called
        //it prints the message to the console and moves on to the next function
        //question: does this execute even though route /a (2) terminates abruptly?
        //app.get('/b' ... does not depend in any way on (2). as url match criteria are different in both middleware, even if /a throws an exception, /b will stay intact. but this middleware will get executed only at /b not /a. i.e. if /a calls next(), this middleware will not get executed.
        app.get('/b', function(req, res, next){
                    console.log('/b: route not terminated');
        next();
        });
    
        //5. question: this gets called after above (4)?
        //Yes, as (4) calls next(), this middleware gets executed as this middleware does not have a url filter pattern.
        app.use(function(req, res, next){ 
          console.log('SOMETIMES');
          next();
        });
    
        //6. question: when does this get executed? There is already a function to handle when GET on /b is called (4)
       //As (4) calls next(), (5) gets called, again (5) calls next() hence this is called. if this was something other '/b' like '/bbx' this wouldn't get called --- hope this makes sense, url part should match.
        app.get('/b', function(req, res, next){
          console.log('/b (part 2): error thrown' );
          throw new Error('b failed');
        });
    
        //7. question: I am not sure when this gets called... ?
        // This happens (4) calls next() -> (5) calls next() -> (6) throws exception, hence this special error handling middleware that catches error from (6) and gets executed. If (6) does not throw exception, this middleware won't get called.
        //Notice next(err) this will call (10). -- as we are passing an error
        app.use('/b', function(err, req, res, next){
          console.log('/b error detected and passed on');
          next(err);
        });
    
        //8. this is executed when a GET request is made on route /c. It logs to the console; throws an error.
        app.get('/c', function(res, req){
          console.log('/c: error thrown');
          throw new Error('c failed');
        });
    
        //9. question: this catches the above error and just moves along?
        //Yes, as this middleware calls next(), it will move to next matching middleware. so it will call (11) and not (10) because (10) is error handling middleware and needs to be called like next(err)
        app.use('/c', function(err, req, res, next) {
          console.log('/c: error deteccted but not passed on');
          next();
        });
    
        //10. question: this follows the above and prints an error based on above?
        //Which ever middleware from above calls next(err) will end up calling this one. ie. (7) does so.
        //This also sends a 500 response?
        //This just sends text as '500 - server error'
        //in order to set status code you'll need to do res.status(500).send ...
        app.use(function(err, req, res, next){
          console.log('unhandled error detected: ' + err.message);
          res.send('500 - server error');
          //Also set status code
          //res.status(500).send('500 - server error');
        });
    
        //11. question: this is the catch all for something that falls through and sends a 404?
        //No, this does not catch error, as in (7). This route will get elected       when non of the above middleware were able to respond and terminate the chain. So this is not an error handling route, this route just sends 404 message if non of the above routes returned a response and stopped chain of execution
        app.use(function(req, res){
          console.log('route not handled');
          res.send('404 - not found');
          //Also set status code
          //res.status(400).send('404 - not found');
        });
    
        //12. This app listens on the 3000 port.
        app.listen(3000, function(){
                    console.log('listening on 3000');
        });
    

    希望这有助于您了解流程。

    如果您需要更多说明,请告诉我。

    【讨论】:

      【解决方案3】:

      中间件很好用,但起初有点难以理解。 在中间件中要记住的最重要

    • 序列
    • next() 函数
    • 序列
      正如前面的答案中提到的,排序在中间件中非常重要。由于中间件是一个接一个的执行,所以尽量严格自上而下的理解代码
      app.use(function(req,res,next){
      

      由于上述代码没有指定任何路由,例如 /a 或 /b,因此每次调用 API 时都会执行这种类型的中间件。所以这个中间件会一直被执行。`

      app.use(function(err,req,res,next){
      

      了解当 app.use 有 4 个参数时,Express 将其识别为错误处理中间件。因此,在执行时抛出或创建的任何错误都将通过此中间件。
      因此,#11 NOT 是一个错误处理中间件。它只是停止中间件链,因为它没有 next() 函数 AND 它是序列中的最后一个中间件。
      你现在也应该明白 #7 是一个错误处理中间件,它从 #6 中得到错误,用于 /b 路由。 #7 处理 err 中传入的错误,然后将错误参数传递给 next() 函数。

      next()
      next() 只是沿链传递控制的函数。如果您觉得一个中间件不足以满足该特定路由(甚至没有路由),您可以调用 next() 函数,该函数会将控制权传递给下一个有效的中间件。
      您可以使用路由指定有效性,或使其具有通用性,例如#9 和#10。来自 #9 的错误不会传递给 #10。这是因为 #9 中的 next() 没有传递 err 参数,因此作为错误处理中间件的 #10 不会捕获它。 #9 将到达 #11

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-27
        • 2017-11-16
        • 2017-03-27
        • 1970-01-01
        • 2014-09-11
        • 2018-10-05
        • 2019-09-17
        • 1970-01-01
        相关资源
        最近更新 更多