Koa2學習系列03-路由koa-router——MVC 中重要的環節:Url 處理器
路由 koa-router
上一節我們學習了中介軟體的基本概念,本節主要帶大家學習下
koa-router
路由中介軟體的使用方法。
路由是用於描述 URL
與處理函式之間的對應關係的。比如使用者訪問 http://localhost:3000/
,那麼瀏覽器就會顯示 index
頁面的內容,如果使用者訪問的是 http://localhost:3000/home
,那麼瀏覽器應該顯示 home
頁面的內容。
要實現上述功能,如果不借助 koa-router
或者其他路由中介軟體,我們自己去處理路由,那麼寫法可能如下所示:
const Koa = require('koa'); const app = new Koa(); app.use(async (ctx, next) => { if (ctx.request.path === '/') { ctx.response.body = '<h1>index page</h1>'; } else { await next(); } }); app.use(async (ctx, next) => { if (ctx.request.path === '/home') { ctx.response.body = '<h1>home page</h1>'; } else { await next(); } }); app.use(async (ctx, next) => { if (ctx.request.path === '/404') { ctx.response.body = '<h1>404 Not Found</h1>'; } else { await next(); } }); app.listen(3000, ()=>{ console.log('server is running at http://localhost:3000') })
把上述程式碼複製並覆蓋到 app.js
中,然後執行以下命令啟動 node
程式:
node app.js
啟動之後在瀏覽器中分別訪問 http://localhost:3000/
、http://localhost:3000/home
、http://localhost:3000/404
就能看到相應的頁面了。
上述 app.js
的程式碼中,由 async
標記的函式稱為『非同步函式』,在非同步函式中,可以用 await
呼叫另一個非同步函式,async
await
這兩個關鍵字將在 ES7 中引入。引數 ctx
是由 koa
傳入的,我們可以通過它來訪問 request
和 response
,next
是 koa
傳入的將要處理的下一個非同步函式。
注意: 由於 node
在 v7.6.0
中才支援 async
和 await
,所以在執行 app.js
之前請確保 node 版本正確,或者使用一些第三方的 async
庫來支援。
這樣的寫法能夠處理簡單的應用,但是,一旦要處理的 URL
多起來的話就會顯得特別笨重。所以我們可以藉助 koa-router
來更簡單的實現這一功能。 下面來介紹一下如何正確的使用 koa-router
。
安裝 koa-router
通過 npm
命令直接安裝:
npm i koa-router -S
-S
或者 --save
是為了安裝完成之後能夠在 package.json
的 dependencies
中保留 koa-router
,以便於下次只需要執行 npm i
或者 npm install
就能夠安裝所有需要的依賴包。
基本使用方法
如果要在 app.js
中使用 koa-router
來處理 URL
,可以通過以下程式碼來實現:
const Koa = require('koa') // 注意 require('koa-router') 返回的是函式: const router = require('koa-router')() const app = new Koa() // 新增路由 router.get('/', async (ctx, next) => { ctx.response.body = `<h1>index page</h1>` }) router.get('/home', async (ctx, next) => { ctx.response.body = '<h1>HOME page</h1>' }) router.get('/404', async (ctx, next) => { ctx.response.body = '<h1>404 Not Found</h1>' }) // 呼叫路由中介軟體 app.use(router.routes()) app.listen(3000, ()=>{ console.log('server is running at http://localhost:3000') })
執行 app.js
:
node app.js
執行完上面的操作之後,我們在瀏覽器中訪問 http://localhost:3000/
:
在瀏覽器中訪問 http://localhost:3000/home
:
在瀏覽器中訪問 http://localhost:3000/404
:
通過上面的例子,我們可以看到和之前不使用 koa-router
的顯示效果是一樣的。不過使用了 koa-router
之後,程式碼稍微簡化了一些,而且少了 if
判斷,還有省略了 await next()
(因為沒有其他中介軟體需要執行,所以這裡就先省略了)。
當然,除了 GET
方法,koa-router
也支援處理其他的請求方法,比如:
router .get('/', async (ctx, next) => { ctx.body = 'Hello World!'; }) .post('/users', async (ctx, next) => { // ... }) .put('/users/:id', async (ctx, next) => { // ... }) .del('/users/:id', async (ctx, next) => { // ... }) .all('/users/:id', async (ctx, next) => { // ... });
在任意http請求中,遵從 RESTful
規範,可以把 GET
、POST
、PUT
、DELETE
型別的請求分別對應 查
,增
,改
,刪
,這裡 router
的方法也一一對應。通常我們使用 GET
來查詢和獲取資料,使用 POST
來更新資源。PUT
和 DELETE
使用比較少,但是如果你們團隊採用 RESTful架構
,就比較推薦使用了。我們注意到,上述程式碼中還有一個all
方法。all
方法通常用於匹配一組路由或者全部路由從而做一些統一設定和處理,也可以處理不確定客戶端傳送的請求方法型別的情況。
舉個例子,假設客戶端使用 jQuery
來開發,有如下幾個 ajax
請求:
// 優先匹配和 router.get 方法中 url 規則一樣的請求,如果匹配不到的話就匹配和 router.all 方法中 url 規則一樣的請求。 $.ajax({ method: "GET", url: "some.php", data: { name: "John" } }).done(function( msg ) { // do something }); // 優先匹配和 router.post 方法中 url 規則一樣的請求,如果匹配不到的話就匹配和 router.all 方法中 url 規則一樣的請求。 $.ajax({ method: "POST", url: "some.php", data: { name: "John" } }).done(function( msg ) { // do something });
上面例子中兩個方法最主要的區別就是 ajax
中 method
的值,method
的值和 router
的方法一一對應。
再舉一個使用all
方法的例子,假設我們要為所有請求設定跨域頭,可以通過如下程式碼實現:
router.all('/*', async (ctx, next) => { // *代表允許來自所有域名請求 ctx.set("Access-Control-Allow-Origin", "*"); // 其他一些設定... await next(); });
這段程式碼表示對於所有請求,允許來自所有域名。這是一種很危險的做法,在真實專案中一定不能這麼做。
*
號是一種萬用字元,表示匹配任意 URL
。這裡的返回是一種簡化的寫法,真實開發中,我們肯定要去讀取 HTML
檔案或者其他模板檔案的內容,再響應請求。關於這部分的內容後面的章節中會詳細介紹。
另外,如果一條路由在`all`方法和其他方法中同時命中,只有執行了`await next()`,那麼這條路由會在`all`方法和其他方法中都會起作用,舉個例子,看如下程式碼:
const Koa = require('koa') const router = require('koa-router')() const app = new Koa() // 新增路由 router.get('/', async (ctx, next) => { ctx.response.body = `<h1>index page</h1>` await next(); }) router.all('/', async (ctx, next) => { console.log('match "all" method') await next(); }); // 呼叫路由中介軟體 app.use(router.routes()) app.listen(3000, ()=>{ console.log('server is running at http://localhost:3000') })
執行這段程式碼,我們不僅能夠訪問http://localhost:3000/看到“index page”,也能夠在控制檯中看到“'match "all" method'”,說明路由"/"不僅執行了get
方法的回撥,也執行了all
方法的回撥函式。但是,如果我們把get
方法中的await next()
去掉,那麼就不會命中all
方法的路由規則,也不會執行all
方法的回撥函數了。因為說到底,對路由的處理也是一種中介軟體,如果不執行await next()
把控制權交給下一個中介軟體,那麼後面的路由就不會再執行了。
其他特性
命名路由
在開發過程中我們能夠很方便的生成路由 URL
:
router.get('user', '/users/:id', function (ctx, next) { // ... }); router.url('user', 3); // => 生成路由 "/users/3" router.url('user', { id: 3 }); // => 生成路由 "/users/3" router.use(function (ctx, next) { // 重定向到路由名稱為 “sign-in” 的頁面 ctx.redirect(ctx.router.url('sign-in')); })
router.url
方法方便我們在程式碼中根據路由名稱和引數(可選)去生成具體的 URL
,而不用採用字串拼接的方式去生成 URL
了。
多中介軟體
koa-router
也支援單個路由多中介軟體的處理。通過這個特性,我們能夠為一個路由新增特殊的中介軟體處理。也可以把一個路由要做的事情拆分成多個步驟去實現,當路由處理函式中有非同步操作時,這種寫法的可讀性和可維護性更高。比如下面的示例程式碼所示:
router.get( '/users/:id', function (ctx, next) { return User.findOne(ctx.params.id).then(function(user) { // 首先讀取使用者的資訊,非同步操作 ctx.user = user; next(); }); }, function (ctx) { console.log(ctx.user); // 在這個中介軟體中再對使用者資訊做一些處理 // => { id: 17, name: "Alex" } } );
巢狀路由
我們可以在應用中定義多個路由,然後把這些路由組合起來用,這樣便於我們管理多個路由,也簡化了路由的寫法。
var forums = new Router(); var posts = new Router(); posts.get('/', function (ctx, next) {...}); posts.get('/:pid', function (ctx, next) {...}); forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods()); // 可以匹配到的路由為 "/forums/123/posts" 或者 "/forums/123/posts/123" app.use(forums.routes());
路由字首
通過 prefix
這個引數,我們可以為一組路由新增統一的字首,和巢狀路由類似,也方便我們管理路由和簡化路由的寫法。不同的是,字首是一個固定的字串,不能新增動態引數。
var router = new Router({ prefix: '/users' }); router.get('/', ...); // 匹配路由 "/users" router.get('/:id', ...); // 匹配路由 "/users/:id"
URL 引數
koa-router
也支援引數,引數會被新增到 ctx.params
中。引數可以是一個正則表示式,這個功能的實現是通過 path-to-regexp
來實現的。原理是把 URL
字串轉化成正則物件,然後再進行正則匹配,之前的例子中的 *
萬用字元就是一種正則表示式。
router.get('/:category/:title', function (ctx, next) { console.log(ctx.params); // => { category: 'programming', title: 'how-to-node' } });
通過上面的例子可以看出,我們可以通過 ctx.params
去訪問路由中的引數,使得我們能夠對引數做一些處理後再執行後續的程式碼。
使用了 koa-router
之後,程式碼簡潔了很多。下一節中,我們將學習下如何響應瀏覽器的各種請求。