2-1 koa 简介
- 由 Express 幕后的原班人马打造
- web 应用和 API 开发领域
- 更小、更富有表现力、更健壮
- 利用async函数,丢弃回调函数
- 增强错误处理:try catch
- 没有捆绑任何
2-2 安装搭建第一个 Koa 程序
- 初始化项目
- 安装 Koa
- 编写 Hello World
- 学习自动重启
npm i koa --save
index.js
const koa = require('koa')
const app = new koa()
app.use((ctx) => {
ctx.body = 'Hello World'
})
app.listen(3000)
2-3 Koa中间件与洋葱模型
- 学习 async await
- 学习编写 Koa 中间件
- 学习洋葱模型
回调写法
fetch('//api.github.com/users').then(res =>
res.json()).then(json => {console.log(json)
fetch('//api.github.com/users/lewis617').then(res =>
res.json()).then(json => {console.log(json)
})
})
async await
(async () => {
const res = await fetch('//api.github.com/users')
const json = await res.json()
console.log(json)
const res2 = await fetch('//api.github.com/users/lewis617')
const json2 = await res2.json()
console.log(json2)
})()
中间件执行
const koa = require('koa')
const app = new koa()
app.use(async (ctx, next) => {
await next()
console.log(1)
ctx.body = 'Hello World'
})
app.use(async (ctx, next) => {
await next()
console.log(2)
})
app.listen(3000)
输出: 2 1
由于在第一个中间件中用到了async await,await next()到了第二个中间件执行完打印2然后打印第一个中间件的1.