koa是一個(gè)新的web框架,致力于成為web應(yīng)用和API開發(fā)領(lǐng)域中一個(gè)更小、更富有表現(xiàn)力,更健壯的基石。
koa是express的下一代基于Node.js的web框架
koa2完全使用Promise并配合async來實(shí)現(xiàn)異步
為什么需要koa
1request和response并沒有那么優(yōu)雅,偏向理論的api
2復(fù)雜異步邏輯處理
安裝: npm i koa -S
//引入
const koa = require('koa')
//初始化
const app = new koa()
//第一個(gè)中間件 app.use使用中間件
app.use(async (ctx,next) => {
const start = new Date().getTime()
console.log(`start:${ctx.url}`)
//next就是走第二個(gè)中間件 如果第二個(gè)中間件里面沒有其他中間件 就會(huì)返回往下執(zhí)行
await next()
const end = new Date().getTime()
console.log(`請求${ctx.url} 耗時(shí)${parseInt(end - start)}ms`)
})
//第二個(gè)中間件
//起一個(gè)http服務(wù)
app.use((ctx,next) => {
console.log('==============')
//返回一個(gè)json http的body
ctx.body = [
{
name: 'tom'
}
]
})
//監(jiān)聽3000
app.listen(3000)