koa --- 自制简易的koa-router
生活随笔
收集整理的這篇文章主要介紹了
koa --- 自制简易的koa-router
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
打算自己寫一個(gè)簡單的Router類,來實(shí)現(xiàn)koa-router這個(gè)中間件的(部分)神奇功能
確定需求
1.首先導(dǎo)入需要在app.js里面導(dǎo)入自己寫的Router類
2.然后是使用的方式和掛載router的方式
設(shè)計(jì)
- 以上只是部分代碼,在本篇的結(jié)尾會(huì)貼出整體代碼.
- 上面設(shè)計(jì)到Router實(shí)例(router)的2個(gè)方法:get和routes.
- get():接受了2個(gè)參數(shù),一個(gè)是需要處理的url,一個(gè)是對(duì)應(yīng)路由的路由事件處理函數(shù).該方法,將處理的路由和路由處理事件存入一個(gè)數(shù)組中,因此需要一個(gè)_routes的私有數(shù)組
- routes():app.use里面接受的是一個(gè)async函數(shù),因此在routes方法中,需要返回一個(gè)async函數(shù),當(dāng)收到來自客戶端的url請求后(url的信息被存儲(chǔ)在ctx中),需要根據(jù)請求方法和url地址,找到_routes中對(duì)應(yīng)的處理函數(shù),然后等待執(zhí)行. await…
實(shí)現(xiàn)
// 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;補(bǔ)充
完整的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);總結(jié)
以上是生活随笔為你收集整理的koa --- 自制简易的koa-router的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA背景颜色及背景图片设置
- 下一篇: RT-Thread设备框架学习感悟