白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——中间层模式

介绍

中间层模式(Middleware Pattern),也称为拦截器模式(Interceptor Pattern)或过滤器模式(Filter Pattern),是一种用于处理请求的设计模式。它允许在请求的发送者和接收者之间插入中间层,以便在处理请求前后执行额外的逻辑或操作。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
// Express 中间件
function logger(req, res, next) {
console.log('Request:', req.method, req.url);
next(); // 调用next()将请求传递给下一个中间件或路由处理函数
}

// 使用中间件
app.use(logger);

// 路由处理函数
app.get('/home', function(req, res) {
res.send('Welcome to the homepage');
});