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

91 阅读1分钟

介绍

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

代码

// 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');
});