中间件

PPG007 ... 2023-5-9 Less than 1 minute

# 中间件

import koa =  require('koa');
const app = new koa();

app.use(async (ctx, next) => {
    console.log('start');
    await next();
    console.log('end');
})
app.use((ctx) => {
    ctx.body = 'Hello World';
    console.log('running');
});
app.listen(8080, '0.0.0.0');
1
2
3
4
5
6
7
8
9
10
11
12
13

Note

注意 use 方法的调用顺序。

# 多个中间件结合

import compose = require('koa-compose');

async function random(ctx: koa.ParameterizedContext, next: koa.Next) {
  if ('/random' == ctx.path) {
    ctx.body = Math.floor(Math.random() * 10);
  } else {
    await next();
  }
};

async function backwards(ctx: koa.ParameterizedContext, next: koa.Next) {
  if ('/backwards' == ctx.path) {
    ctx.body = 'sdrawkcab';
  } else {
    await next();
  }
}

async function pi(ctx: koa.ParameterizedContext, next: koa.Next) {
  if ('/pi' == ctx.path) {
    ctx.body = String(Math.PI);
  } else {
    await next();
  }
}

const all = compose([random, backwards, pi]);

app.use(all);
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
Last update: May 9, 2023 09:46
Contributors: Koston Zhuang