Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Created August 14, 2019 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlid/f7abf2938cf651d1c9f8475f804db51c to your computer and use it in GitHub Desktop.
Save ryanlid/f7abf2938cf651d1c9f8475f804db51c to your computer and use it in GitHub Desktop.
koa 简单的路由示例
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)
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