ExpressJS中的路由(“下一个”)是做什么的?
在文档中说:
您可以提供多个callback函数,其行为与中间件类似,除了这些callback可以调用next('route')来绕过剩余的路由callback。 您可以使用此机制在路线上施加先决条件,如果没有理由继续当前路线,则将控制权交给后续路线。
这是否意味着如果我写这样的路线:
app.get('/', function(req, res, next) { if (!req.params.id) { res.statusCode(400).send({error: "id parameter is required"}); next('route'); } else { next(); } }, function(req, res) { res.send({something: 'something'}) });
和params.id
是undefined
,那么下一个路由不会被执行,但如果它存在,它会?
基本上编码/命名约定是有点混淆我。 为什么不下next(false)
而不是下next('route')
?
我find了答案。 使用app
或Express路由器时,可以为同一path定义多个路由:
// first set of routes for GET /user/:id app.get('/user/:id', function (req, res, next) { // logic }, function (req, res, next) { // logic }); // second set of routes for GET /user/:id app.get('/user/:id', function (req, res, next) { // logic });
如果来自第一个路由的任何callback(中间件),则调用next('route')
, 则该组路由的所有callback将被跳过,并将控制传递给下一组路由:
// first set of routes for GET /user/:id app.get('/user/:id', function (req, res, next) { next('route') }, function (req, res, next) { // this middleware won't be executed at all }); // second set of routes for GET /user/:id app.get('/user/:id', function (req, res, next) { // the next('route') in the first callback of the first set of routes transfer control to here });
现在使用next('route')
而不是next(false)
更有意义:它将控制转移到为当前path定义的下一个路由。
(如果)params.id是未定义的,那么下一个路由将不会被执行,但如果它存在,它会?
主要思想是检查文件中的下一个路由。
从重复的问题 ,这在很多,更详细的答案:
next()没有参数说“只是在开玩笑,我实际上不想要处理这个”。 它回来,并试图find下一个匹配的路线。