# 基础中间件实现
# express 中间件使用
var express = require('express');
var app = express();
app.use(function(req, res, next) {
console.log('数据统计');
next(); // 执行下一步
});
app.use(function(req, res, next) {
console.log('日志统计');
next(); // 执行下一步
});
app.get('/', function(req, res, next) {
res.send('Hello World!');
});
app.listen(3000);
// 整个请求处理过程就是先数据统计、日志统计,最后返回一个Hello World!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 基础实现
class Middleware {
constructor(params) {
this.params = params;
this.middlewares = []
}
next(){
if(!this.middlewares.length)return ;
const middleware = this.middlewares.shift()
middleware(this.params, this.next.bind(this))
}
use(fn){
this.middlewares.push(fn)
return this;
}
go(){
this.next()
}
}
const app = new Middleware({})
app.use((ctx, next) => {
ctx.name = 'Liu'
next()
})
app.use((ctx, next) => {
ctx.age = '26'
next()
})
app.use((ctx, next) => {
console.log(`${ctx.name} is ${ctx.age} years old.`)
next()
})
app.go()
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
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