koa 2.x use express-style middlewares
app.use=app.em=app.expressmiddleware支持Express风格的中间件app._use依然可以使用Koa 2.x的三种中间件
$ npm i -S ekoa
最常见的用法
const Koa = require('ekoa')
const app = new Koa()
// log1
app.use(function(req, res, next){
const start = new Date();
return next().then(() => {
const ms = new Date() - start;
console.log(`${req.method} ${req.url} - ${ms}ms`);
});
})
// log2
app.use(function(req, res, next){
console.log('start')
next()
})
app.use(function(req, res, next){
console.log('process')
res.body = "Hello Koa 1";
})
// response
app._use(ctx => {
ctx.body = 'Hello Koa 2'
})
app.run(4000)
支持async函数
const Koa = require('.')
const app = new Koa('sss',{})
// log1
app.use(async function(req, res, next){
const start = new Date();
await next()
const ms = new Date() - start;
console.log(`${req.method} ${req.url} - ${ms}ms`);
})
// log2
app.use(async function(req, res, next){
console.log('start')
await next()
})
app.use(function(req, res, next){
console.log('process')
res.body = "Hello Koa 1";
})
// response
app._use(ctx => {
ctx.body = 'Hello Koa 2'
})
app.run(4000)
通过runkoa执行即可(或babel,或者node 7+)
app.em = app.expressmiddleware
function(req, res, next){
console.log('start')
return next().then(function (){
console.log('end')
})
}
next和koa commonfunction中的next是一样的。
更简单的写法
app.use(function(req, res, next){
console.log('start')
next()
})
function(req, res){
res.body = "xxx"
}
此种写法有先后顺序,没有next中间件就不会向下传递。
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
- v1.0.0 初始化版本
- write by
i5tingi5ting@126.com
如有建议或意见,请在issue提问或邮件
this repo is released under the MIT License.