1.0.5 • Published 9 years ago
ekoa v1.0.5
ekoa:我想把Koa 2.x写的跟express一样
koa 2.x use express-style middlewares
Features
- app.use=- app.em=- app.expressmiddleware支持Express风格的中间件
- app._use依然可以使用Koa 2.x的三种中间件
Install
$ npm i -S ekoaUsages
最常见的用法
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+)
可使用的express风格的中间件
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中间件就不会向下传递。
Contributing
- 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 初始化版本
欢迎fork和反馈
- write by i5tingi5ting@126.com
如有建议或意见,请在issue提问或邮件
License
this repo is released under the MIT License.