正确理解 Expres.js 中的 Route 和中间件(middleware)的关系

45 篇文章 0 订阅
12 篇文章 0 订阅

在 StackOverflow 上看到的,解释比较详细,于是翻译了部分内容:

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

    //1. when this *middleware* is called, this is printed to the console, always.
    //因为这是第一个注册的中间件,没有 url 可匹配,因此这个中间件无论什么 url 访问都会执行。
    //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. 当用户访问 /a 路径,将收到 'a' 的回复。
    //并且这次请求执行结束,因为这个中间件没有调用 next()。
    app.get('/a', function(req, res, next){ 
         console.log('/a: route terminated'); 
         res.send('a');
    });

    //3. 这个中间件不会执行,因为步骤 2 没有调用 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');
    });
https://stackoverflow.com/a/35681961/3054511
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值