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

程式猿小卡_casper發表於2018-02-07

文章概覽

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

背景:關於next()的問題

使用過Express的同學都知道,通過next()將程式碼執行權轉移到下一個中介軟體(例子略)。

在官網有下面例子,出現了next('route')的呼叫:

// 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()有什麼區別呢?上面程式碼實現的效果,用如下程式碼實現不是更簡單嗎:

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

在SF上也有同學表達了同樣的疑惑《對express 應用級中介軟體next('route') 方法例項的疑惑》。

相信有同樣疑惑的同學不少,因為官網對next('route')用法的介紹有點簡略。下文將從Express的路由分組機制來講回答這個問題。

Express路由分組機制

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

Express中,路由是以組的形式新增的。什麼意思呢,可以看下面虛擬碼

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

在內部,Express把上面新增的路由,分成了兩個組。繼續看虛擬碼,可以看到,路由在內部被分成了兩個組。

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

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

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周邊相關的技術文章 :-)

相關文章