Created
August 14, 2019 06:12
-
-
Save ryanlid/f7abf2938cf651d1c9f8475f804db51c to your computer and use it in GitHub Desktop.
koa 简单的路由示例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Koa = require('koa'); | |
const app = new Koa() | |
const Router = require("./router"); | |
const router = new Router(); | |
router.get('/',(context,next)=>{ | |
context.body = 'index Page' | |
}) | |
router.get('/hello',(context,next)=>{ | |
context.body = 'Hello Page' | |
}) | |
router.get('/404',(context,next)=>{ | |
context.body = 'Page not Found' | |
}) | |
app.use(router.routes()) | |
app.listen(3000) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Router { | |
constructor() { | |
// 缓存路由规则 | |
this._routes = []; | |
} | |
// 设置Method为GET的路由规则 | |
get(url, handler) { | |
this._routes.push({ | |
url: url, | |
methods: "GET", | |
handler | |
}); | |
} | |
// 返回路由处理中间件给Koa使用 | |
routes() { | |
return async (ctx, next) => { | |
// 返回当前请求的URL和Method | |
const { method, url } = ctx; | |
const matchedRouter = this._routes.find( | |
r => r.methods === method && url === r.url | |
); | |
// 从缓存的规则中找出匹配的规则 | |
if (matchedRouter && matchedRouter.handler) { | |
// 执行路由规则中的处理函数,响应请求 | |
await matchedRouter.handler(ctx, next); | |
} else { | |
await next(); | |
} | |
}; | |
} | |
} | |
module.exports = Router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment