中间件
自定义中间件
typescript
import Koa from "koa";
const app = new Koa()
// 第一个自定义中间件
const one = async (ctx: Koa.Context, next: Koa.Next) => {
console.log('one-1')
await next()
console.log('one-2')
}
// 第二个自定义中间件
const two = async (ctx: Koa.Context, next: Koa.Next) => {
console.log('two-1')
await next()
console.log('two-2')
}
app
.use(one)
.use(two)
.use(async (ctx: Koa.Context) => {
ctx.response.body = '来试试自定义中间件'
})
app.listen(3000)
/*
* output
one-1
two-1
two-2
one-2
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
其他中间件
router
用法:用法
相关文档:@koa/router
bash
npm install @koa/router
npm install @types/koa__router -D
1
2
2
koa-body
- 用法:用法
- 相关文档:koa-body - npm (npmjs.com)
- 扩展文档:扩展
npm install koa-static
npm i --save-dev @types/koa-static
1
2
2
cors
npm i @koa/cors
npm i @types/koa__cors
1
2
2
typescript
import koa from 'koa';
import cors from "@koa/cors";
const app = new koa()
app.use(cors())
1
2
3
4
5
6
2
3
4
5
6