koa --- 自制简易的koa-router
生活随笔
收集整理的這篇文章主要介紹了
koa --- 自制简易的koa-router
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
打算自己寫一個簡單的Router類,來實現koa-router這個中間件的(部分)神奇功能
確定需求
1.首先導入需要在app.js里面導入自己寫的Router類
2.然后是使用的方式和掛載router的方式
設計
- 以上只是部分代碼,在本篇的結尾會貼出整體代碼.
- 上面設計到Router實例(router)的2個方法:get和routes.
- get():接受了2個參數,一個是需要處理的url,一個是對應路由的路由事件處理函數.該方法,將處理的路由和路由處理事件存入一個數組中,因此需要一個_routes的私有數組
- routes():app.use里面接受的是一個async函數,因此在routes方法中,需要返回一個async函數,當收到來自客戶端的url請求后(url的信息被存儲在ctx中),需要根據請求方法和url地址,找到_routes中對應的處理函數,然后等待執行. await…
實現
// router.js class Router{constructor() {this._routes = [];}get(url, hanlder) {this._routes.push({url: url,method:'GET',handler});}routes() {return async (ctx, next) {const { method, url} =ctxconst matchedRouter = this._routes.find(r => r.method === method && r.url === url);if(matchedRouter && matchedRouter.handler(context, next){await matchedRouter.handler(ctx, next);} else {awai next();}}} } module.exports = Router;補充
完整的app.js
const koa = require('koa'); const app = new koa() const Router = require('./components/router.js'); const router = new Router();router.get('/404', (ctx, next) => {ctx.body = 'Page not found';ctx.status = 404; }); app.use(router.routes()).listen(3000);總結
以上是生活随笔為你收集整理的koa --- 自制简易的koa-router的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA背景颜色及背景图片设置
- 下一篇: RT-Thread设备框架学习感悟