控制流的返回如何在一系列Express中间件功能中起作用



我实际上有几个有关快速中间件链条的问题,并认为我会在这篇文章中分组,因为它们密切相关。


Q1:在中间软件功能中,如果我 send() CC_1,将传递给下一个函数,或者只是返回,剩下的任何代码是否被执行?

router.get('/a', (req, res, next) => {
    res.sendStatus(200);
    // Does this ever get executed?
}); 
router.get('/b', (req, res, next) => {
    next();
    // Does this ever get executed?
}); 
router.get('/c', (req, res, next) => {
    return;
    // Does this stop the middleware chain? What happens to the request/response?
});

Q2:您可以从前面的内部传递到另一个中间件功能吗?我的理由是,我必须提供一个参数来创建某个中间件,并且该参数取决于express app对象是 Request的所有者。因此,我需要在将请求的属性传递给需要使用该属性创建的中间件之前访问该请求的属性。这可以工作:?

router.get('/d', (req, res, next) => {
    var middlewareFunction = createDynamicMiddleware();
    middlewareFunction(req, res, next); // Will this still work as expected?
});

Q3:当您致电next()而没有任何参数时,Request/Response参数如何传递给下一个中间件?

Q1 :在中间件功能中,如果我发送((响应,传递给下一个函数或仅返回,则其余的代码会获取 执行?

router.get('/a', (req, res, next) => {
    res.sendStatus(200);
    // Does this ever get executed?
    //    Yes, but don't call next() or res.send() or it will throw an error
}); 
router.get('/b', (req, res, next) => {
    next();
    // Does this ever get executed?
    //    Yes, but don't call next() or res.send() or it will throw an error
}); 
router.get('/c', (req, res, next) => {
    return;
    // Does this stop the middleware chain? What happens to the request/response?
    //    The request get stuck and after a while it will fail due 'timeout'
});

Q2 :您可以从上一个内部的另一个中间件功能传递到另一个中间件功能吗?我的理由是我必须提供 创建某个中间件的论点,该参数是 取决于哪个Express App对象是请求的所有者。所以 我需要在将请求的属性传递给该请求之前访问 需要使用该属性创建的中间件。

您的动态中间件工厂应返回新功能

返回新功能的函数也被称为咖喱功能,这是一个实际示例:

// based on 'someId' we will return a specific middleware
req.get('/user/:someId', 
 createDynamicMiddleware,
 (req,res) => { 
  res.send('ok') 
 })
function createDynamicMiddleware(req,res,next){
  if(req.params.someId === 'me') {
    return function(req, res, next){
     // do some stuff if someId is me
     return next();
    }
  } else {
    return function(req, res, next){
     // do some other stuff otherwise
     return next();
    }
  }
}

Q3 :当您致电Next((无参数时,请求/响应参数如何传递给下一个中间件?

Express为您处理此操作!

另外,如果您将属性添加到REQ或RES对象,则将存在于下一个Middlewares

例如:

router.get('/', (req,res,next) => {
  req.customProperty = 'hello!';
  return next();
}, (req, res) => {
  console.log(req.myCustomProperty)
  // hello!
})

最新更新