Koa对比Express
Express的中间件是线型的,调用next就放行,执行下一个中间件
Koa的中间件是U型,也叫做洋葱模型, 即use多个中间件,先按中间件书写的顺序执行每个中间件awaitnext调用之前的代码,然后按中间件书写的逆序执行中间件await next之后的代码
Koa1使用generator语法
Koa2使用async/await语法
Koa 的ctx.req和ctx.request分别来自于Nodejs和Koa自身
开启一个Koa服务
安装
npm i --save-dev @types/koa
npm i koa
tsc --init
ts-node-dev 01koa_server.ts
import Koa from 'koa'
const app = new Koa()
app.use(async (context) => {
context.body = 'hello koa'
})
app.listen(3000, () => console.log('server run at port 3000'))
中间件
访问3000端口,输出什么?
import Koa from 'koa'
const app = new Koa()
app.use(async (context,next) => {
context.body = '1'
await next()
context.body += ' 3'
})
app.use(async (ctx,next)=>{
ctx.body += ' 2'
await next()
ctx.body += ' 4'
})
app.listen(3000, () => console.log('server run at port 3000'))
答:
1,2,4,3
联想洋葱模型,即U型
先走到1,2,此时到达U的拐点,然后是4,3
设置响应头
import Koa from 'koa'
const app = new Koa()
app.use(async (context, next) => {
context.body = '1'
await next()
context.body += ' 3'
})
app.use(async (ctx, next) => {
ctx.body += ' 2'
await next()
ctx.body += ' 4'
})
// 设置响应头
app.use(async (ctx, next) => {
ctx.set('Content-Type', 'text/html;charset=utf-8')
await next()
})
app.listen(3000, () => console.log('server run at port 3000'))