Express進階:從一個例子看路由分組機制

文章概覽

路由是Express的核心功能。本文經過一個簡單例子,介紹Express的路由分組機制,以及next('route')的正確使用方法。javascript

背景:關於next()的問題

使用過Express的同窗都知道,經過next()將代碼執行權轉移到下一個中間件(例子略)。java

在官網有下面例子,出現了next('route')的調用:node

// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next router
  if (req.params.id === '0') next('route')
  // otherwise pass control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // render a regular page
  res.render('regular')
})

// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id)
  res.render('special')
})
複製代碼

差異就在於多了個參數,它跟普通的的next()有什麼區別呢?上面代碼實現的效果,用以下代碼實現不是更簡單嗎:git

app.get('/user/:id', function (req, res, next) {
  if (req.params.id == 0) {
    res.render('special');
  } else {
    res.render('regular');
  };
})
複製代碼

在SF上也有同窗表達了一樣的疑惑《對express 應用級中間件next('route') 方法實例的疑惑》。github

相信有一樣疑惑的同窗很多,由於官網對next('route')用法的介紹有點簡略。下文將從Express的路由分組機制來說回答這個問題。express

Express路由分組機制

Express的路由內部實現比較複雜,這裏只挑跟題目有關的講。segmentfault

Express中,路由是以組的形式添加的。什麼意思呢,能夠看下面僞代碼bash

app.get('/user/:id', fn1, fn2, fn3);
app.get('/user/:id', fn4, fn5, fn6);
複製代碼

在內部,Express把上面添加的路由,分紅了兩個組。繼續看僞代碼,能夠看到,路由在內部被分紅了兩個組。app

var stack = [
  {path: '/user/:id', fns: [fn1, fn2, fn3], // 路由組1
  {path: '/user/:id', fns: [fn4, fn5, fn5] // 路由組2
];
複製代碼

路由匹配就是個遍歷的過程,略。koa

next('route')是幹嗎的

答案:跳過當前路由分組中,剩餘的handler(中間件)

若是沒有next('route'),一路next()調用下去的話,調用順序是這樣的:

fn1 -> fn2 -> fn3 -> fn4 -> fn5 -> fn6
複製代碼

假設某些狀況下,在執行了fn1後,想要跳過fn2fn3,怎麼辦?(好比樓主舉的例子)

答案就是在fn1裏調用next('route')

而後就變成了

fn1 -> fn4 -> fn5 -> fn6
複製代碼

寫在後面

寫到這裏,相信你們對Express的路由分組機制,以及next('route')的用法都有了必定了解。Express的路由比較複雜,篇幅所限,這裏不繼續展開,感興趣的同窗能夠留言交流。若有錯漏,敬請指出。

Express、koa2略有小研究,最近剛擼了一遍源碼。另外,常年分享周邊科普文,歡迎關注 個人GitHub 程序猿小卡,或者star 《Nodejs學習筆記》

後續會繼續分享Express或koa2周邊相關的技術文章 :-)

相關文章
相關標籤/搜索