如何编写koa框架的中间价?
使用过koa2的朋友们都知道,koa2依赖的中间件不少
1、koa-router
2、koa-bodyparser
3、koa-static
等等....
那我们今天就来编写一个koa2的中间件
简单点的 把所访问的路由全部写变为小写
1、创建工程
安装koa2 等等 koa-router
或者快一点我们使用koa-generator 脚手架来搭建项目
![](https://img.haomeiwen.com/i6825620/5f756da6b45ed427.png)
在根目录中创建middler文件夹用了存放我们自定义中间件的文件
在middler中创建index.js
//middler/index.js
function routerTolowercase(ctx){
//接受koa的请求实体 ctx
ctx.path = ctx.path.pathtoLocaleLowerCase()
console.log('toLowerCase',ctx.path)
}
module.exports = function(){
return async function(ctx,next){
routerTolowercase(ctx)
await next()
}
}
然后在app.js中 require当前文件
app.use(***())
网友评论