简介
koa 是由 Express 原班人马打造的,致力于成为一个更小、更富有表现力、更健壮的 Web 框架。 使用 koa 编写 web 应用,通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套, 并极大地提升错误处理的效率。koa 不在内核方法中绑定任何中间件, 它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手。
依赖
Koa 依赖 node v7.6.0 或 ES2015及更高版本和 async 方法支持
安装
makdir koa-start
cd makdir
webpack init
npm install koa --save
const Koa = require('koa');
const app = new Koa();
app.use(async ctx =>{
ctx.body = "hello World"
});
app.listen(3000)
Async 函数
// 按照官方示例
const Koa = require('koa')
const app = new Koa()
// 记录执行的时间
app.use(async (ctx, next)=>{
let stime = new Date().getTime()
await next()
let etime = new Date().getTime()
ctx.response.type = 'text/html'
ctx.response.body = '<h1>Hello World</h1>'
console.log(`请求地址: ${ctx.path},响应时间:${etime - stime}ms`)
});
app.use(async (ctx, next) => {
console.log('中间件1 doSoming')
await next();
console.log('中间件1 end')
})
app.use(async (ctx, next) => {
console.log('中间件2 doSoming')
// await next();
console.log('中间件2 end')
})
app.use(async (ctx, next) => {
console.log('中间件3 doSoming')
await next();
console.log('中间件3 end')
})
app.listen(3000, () => {
console.log('server is running at http://localhost:3000')
})
输出
server is running at http://localhost:3000
中间件1 doSoming
中间件2 doSoming
中间件3 doSoming
中间件3 end
中间件2 end
中间件1 end
请求地址: /,响应时间:1ms
备注
await next() 的含义是下一个中间完成之后执行await下面的代码