var Koa = require('koa');
var Router = require('koa-router');
var app = new Koa();
var router = new Router();
router.get('/home',(ctx,next)=>{
ctx.body = 'home'
next();
});
router.get('/user', (ctx, next) => {
ctx.body = 'user';
next();
});
app.use(router.routes())
app.use(router.allowedMethods());
复制代码
var Koa = require('koa');
var Router = require('koa-router');
var app = new Koa();
var router = new Router();
//将路由的处理交给中间件
app.use((ctx, next) => {
if (ctx.path === '/' && ctx.method === 'GET') {
ctx.body = '首页'
} else {
next();
}
})
app.use((ctx, next) => {
if (ctx.path === '/user' && ctx.method === 'GET') {
ctx.body = '用户'
} else {
next();
}
});
复制代码
从上面能够知道,若是没有koa-router,其实每一个路由使用的koa注册中间件的形式来进行处理的,这样不利于松耦合和模块化,因此将全部路由的处理逻辑抽离出来组合成一个大的中间件koa-router来处理,最后将大的中间件注册到koa上,若是关于koa中间件原理还不了解,能够参考另外一篇文章koa框架会用也会写—(koa的基础框架)css
既然koa-router也是大的中间件,里面拥有许多小的中间件,那么里面必然也须要用到洋葱模型,洋葱模型的特色:html
若是对于中间件和洋葱模型有疑问的,能够参考koa框架会用也会写—(koa的基础架构)mysql
class Layer {
constructor(path,callback) {
this.path = path //路由路径
this.cb = callback //对应的处理函数
}
}
复制代码
class Router {
constructor() {
this.middles = [];
}
}
module.exports = Router
复制代码
class Router {
constructor() {
this.middles = [];
}
//set,post等同理
get(path,callback) {
const layer = new Layer(path,callback)
this.middles.push(layer)
}
}
module.exports = Router
复制代码
class Router {
constructor(){
this.middles=[];
}
//set,post等同理
get(path,fn){
const layer = new Layer(path,callback)
this.middles.push(layer)
}
compose(){}
routes() {
// 返回一个组合的中间件router.routes供app.use注册
// next是koa-router以后app.use注册的中间件
return async (ctx, next) => {
// 请求的路径
let path = ctx.path;
// 和路径匹配的路由的处理函数
let arr = []
for(let item of this.middles) {
if(item.path === path) {
arr.push(item.cb)
}
}
// 一级路由下面还有二级路由
// 用洋葱模型串联全部匹配路由的处理函数
this.compose(ctx, arr,next);
}
}
}
module.exports = Router
复制代码
class Router {
constructor() {
this.middles = [];
}
//set,post等同理
get(path,callback){
const layer = new Layer(path,callback)
this.middles.push(layer)
}
//arr为匹配的路由集合
compose(ctx,arr,next){
dispatch(index){
// 全部的路由处理完成以后,处理在路由中间件后面app.use注册的中间件
if(index === lasts.length) return next();
let route = arr[index];
route(ctx,()=>{dispatch(index+1)})
}
dispatch(0)
},
return async (ctx, next) => {
// 请求的路径
let path = ctx.path;
// 和路径匹配的路由的处理函数
let arr = []
for(let item of this.middles) {
if(item.path === 'path') {
arr.push(item.cb)
}
}
// 一级路由下面还有二级路由
// 用洋葱模型串联全部匹配路由的处理函数
this.compose(ctx, arr,next);
}
}
module.exports = Router
复制代码
上面的router是简化版的koa-router,它只实现了koa-router中的一级路由,可是倒是能说明koa-router的核心思想,koa-router中添加了use来注册二级路由,同时添加了不少包括重定向等其余逻辑处理sql
koa-router中间件的原理基本就介绍完了,后面一块儿学习kao的其余中间件:数据库