什么是Middleware?中间件的功能和REST API应用
Development

什么是Middleware?中间件的功能和REST API应用

Middleware(中间件)是连接系统组件的中间软件。了解其工作原理、分类、在REST API中的应用以及Laravel中的实际示例。

✦ 快速摘要
Middleware(中间件)是连接系统组件的中间软件。了解其工作原理、分类、在REST API中的应用以及Laravel中的实际示例。
这篇文章怎么样?

Middleware(中间件)是连接系统组件的软件层,在请求到达主应用之前进行处理。本文介绍其工作原理、分类、在REST API中的应用以及Laravel中的实际示例。

什么是Middleware?

Middleware(中间件)是位于操作系统、数据库和应用程序之间的软件层。它充当桥梁,使系统中不同组件能够进行通信和数据交换,不受编程语言或平台限制。

中间件的概念出现于20世纪80年代,当时企业系统需要跨平台集成多个应用。中间件提供统一的抽象层,而非让每个应用自行处理连接——降低复杂性,提高可扩展性。

在现代Web开发中,中间件通常指Express.js、Laravel、Django等框架中的请求/响应处理机制——在HTTP请求到达控制器之前进行拦截和处理。

工作原理

中间件采用管道模式(处理链)运作:

  1. 客户端向服务器发送HTTP请求。
  2. 中间件1拦截请求→执行处理(如:CORS检查)。
  3. 中间件2继续处理(如:JWT令牌认证)。
  4. 中间件3进一步处理(如:日志记录、限流)。
  5. 控制器接收经过中间件处理的请求,执行业务逻辑。
  6. 响应在返回客户端之前,反向通过中间件管道。

每个中间件可以:

  • 转发请求到下一个中间件(调用next())。
  • 阻止请求并立即返回响应(如:401 Unauthorized)。
  • 转换请求/响应(添加头部、转换数据)。

中间件分类

类型 功能 示例
消息中间件(MOM) 系统间异步消息传递 RabbitMQ、Apache Kafka、ActiveMQ
数据库中间件 连接应用与多种数据库 ODBC、JDBC、Sequelize
应用服务器 提供应用运行环境 Tomcat、WildFly、IIS
API/集成中间件 连接和管理服务间的API MuleSoft、Apache Camel、Kong
Web中间件 在Web框架中处理HTTP请求 Express中间件、Laravel中间件
RPC中间件 系统间远程过程调用 gRPC、XML-RPC、JSON-RPC
中间件 vs API网关

中间件处理应用内部逻辑(认证、日志)。API网关管理外部流量(路由、限流、负载均衡)。在微服务架构中,API网关通常内部组合多个中间件。

REST API中的中间件

在REST API中,中间件处理与业务逻辑分离的通用任务:

中间件 功能 示例
认证 通过JWT、OAuth、API Key验证用户 passport.jsjwt-auth
授权 检查资源访问权限 基于角色、基于策略
验证 验证输入数据 express-validator、Form Request
限流 限制时间段内的请求数量 express-rate-limitthrottle
CORS 允许来自其他域的请求 cors中间件
日志 记录请求/响应数据 morganmonolog
压缩 压缩响应以减少带宽 compressiongzip
错误处理 集中式错误处理 Error中间件

Express.js中的认证中间件示例:

JavaScript
 1const authMiddleware = (req, res, next) => {
 2  const token = req.headers.authorization?.split(' ')[1];
 3  if (!token) return res.status(401).json({ error: 'Token required' });
 4
 5  try {
 6    req.user = jwt.verify(token, process.env.JWT_SECRET);
 7    next(); // 传递到下一个中间件/控制器
 8  } catch (err) {
 9    res.status(403).json({ error: 'Invalid token' });
10  }
11};
12
13app.get('/api/profile', authMiddleware, profileController);

什么是应用服务器?功能、优势和应用场景

Laravel中的中间件

Laravel将中间件集成到HTTP管道中,分为3个级别:

  • 全局中间件: 对每个请求运行(如:TrustProxiesHandleCors)。
  • 路由中间件: 分配给特定路由(如:auththrottle)。
  • 中间件组: 组合多个中间件(如:webapi)。

创建自定义中间件:

Bash
1php artisan make:middleware CheckAge
php
1// app/Http/Middleware/CheckAge.php
2public function handle(Request $request, Closure $next)
3{
4    if ($request->age < 18) {
5        return redirect('home');
6    }
7    return $next($request);
8}

注册和使用:

php
1// routes/web.php
2Route::get('/dashboard', function () {
3    // 逻辑
4})->middleware('check.age');

Laravel还支持终止中间件(terminable middleware)——在响应发送给客户端后执行处理(如:记录日志、发送通知)。

优势和应用场景

  • 关注点分离(SoC): 认证、日志、缓存逻辑与业务逻辑分离——代码更清晰,更易维护。
  • 可重用性: 单个中间件可在多个路由/控制器中使用,无需重复代码。
  • 集中安全: 在一个点进行认证、授权和输入验证,而非分散各处。
  • 易扩展: 添加/移除中间件不影响核心应用逻辑。
  • 性能优化: 缓存和压缩中间件优化响应时间。
  • 监控: 日志中间件记录所有请求,便于跟踪和调试。
中间件最佳实践

保持每个中间件简单,只做一件事(单一职责)。正确排序——CORS在认证之前,认证在授权之前。避免在中间件中放置业务逻辑。使用中间件组便于管理。

什么是Laravel?最流行的PHP框架

总结: Middleware(中间件)是现代应用架构中必不可少的中间软件层,从企业系统集成到Web框架中的HTTP请求处理。正确理解和使用中间件有助于构建安全、可扩展、易维护的应用。

参考资料

常见问题

常见问题Q&A
什么是Middleware?
Middleware(中间件)是位于操作系统/数据库和应用程序之间的软件层,帮助各组件进行通信、数据交换和高效处理请求。
Middleware如何工作?
Middleware在请求到达主应用之前进行拦截,执行处理(认证、日志、数据转换),然后转发或返回响应。这个过程形成中间件管道(pipeline)。
Middleware有哪些类型?
包括:消息中间件(MOM)、数据库中间件、应用服务器中间件、API/集成中间件,以及Web中间件(在Express、Laravel、Django等框架中处理HTTP请求)。
Middleware在REST API中有什么作用?
在REST API中,Middleware处理JWT/OAuth认证、日志记录、限流、CORS、输入验证、响应压缩和错误处理等通用任务——与业务逻辑分离。
如何在Laravel中创建Middleware?
使用php artisan make:middleware命令创建,在handle()方法中编写逻辑,在bootstrap/app.php中注册或直接分配给路由/组。Laravel支持全局、路由和组中间件。

Middleware is a software layer that connects system components, processing requests before they reach the main application. This article explains how it works, types, applications in REST API, and practical examples with Laravel.

What is Middleware?

Middleware is a software layer between the operating system, database, and application. It acts as a bridge enabling different system components to communicate and exchange data, regardless of programming language or platform.

The concept of middleware emerged in the 1980s when enterprise systems needed to integrate applications across different platforms. Instead of each application handling its own connections, middleware provides a common abstraction layer — reducing complexity and improving scalability.

In modern web development, middleware typically refers to the request/response processing mechanism in frameworks like Express.js, Laravel, and Django — intercepting and processing HTTP requests before they reach the controller.

How It Works

Middleware operates on a pipeline model (processing chain):

  1. Client sends an HTTP request to the server.
  2. Middleware 1 intercepts the request → performs processing (e.g., CORS check).
  3. Middleware 2 continues processing (e.g., JWT token authentication).
  4. Middleware 3 processes further (e.g., logging, rate limiting).
  5. Controller receives the middleware-processed request, executes business logic.
  6. Response travels back through the middleware pipeline before reaching the client.

Each middleware can:

  • Forward the request to the next middleware (call next()).
  • Block the request and return a response immediately (e.g., 401 Unauthorized).
  • Transform the request/response (add headers, transform data).

Middleware Types

Type Function Examples
Message-Oriented (MOM) Asynchronous messaging between systems RabbitMQ, Apache Kafka, ActiveMQ
Database Middleware Connects applications to multiple database types ODBC, JDBC, Sequelize
Application Server Provides application runtime environment Tomcat, WildFly, IIS
API/Integration Connects and manages APIs between services MuleSoft, Apache Camel, Kong
Web Middleware Processes HTTP requests in web frameworks Express middleware, Laravel middleware
RPC Middleware Remote procedure calls between systems gRPC, XML-RPC, JSON-RPC
Middleware vs API Gateway

Middleware handles logic inside the application (authentication, logging). API Gateway manages external traffic (routing, rate limiting, load balancing). In microservices, an API Gateway often combines multiple middleware internally.

Middleware in REST API

In REST APIs, middleware handles common tasks separated from business logic:

Middleware Function Examples
Authentication Verifies users via JWT, OAuth, API Key passport.js, jwt-auth
Authorization Checks resource access permissions Role-based, Policy-based
Validation Validates input data express-validator, Form Request
Rate Limiting Limits requests per time period express-rate-limit, throttle
CORS Allows requests from other domains cors middleware
Logging Logs request/response data morgan, monolog
Compression Compresses responses to reduce bandwidth compression, gzip
Error Handling Centralized error processing Error middleware

Example authentication middleware in Express.js:

JavaScript
 1const authMiddleware = (req, res, next) => {
 2  const token = req.headers.authorization?.split(' ')[1];
 3  if (!token) return res.status(401).json({ error: 'Token required' });
 4
 5  try {
 6    req.user = jwt.verify(token, process.env.JWT_SECRET);
 7    next(); // Pass to next middleware/controller
 8  } catch (err) {
 9    res.status(403).json({ error: 'Invalid token' });
10  }
11};
12
13app.get('/api/profile', authMiddleware, profileController);

What is an Application Server? Features, Benefits and Use Cases

Middleware in Laravel

Laravel integrates middleware into its HTTP pipeline at 3 levels:

  • Global Middleware: Runs for every request (e.g., TrustProxies, HandleCors).
  • Route Middleware: Assigned to specific routes (e.g., auth, throttle).
  • Middleware Group: Groups multiple middleware (e.g., web, api).

Creating custom middleware:

Bash
1php artisan make:middleware CheckAge
php
1// app/Http/Middleware/CheckAge.php
2public function handle(Request $request, Closure $next)
3{
4    if ($request->age < 18) {
5        return redirect('home');
6    }
7    return $next($request);
8}

Register and use:

php
1// routes/web.php
2Route::get('/dashboard', function () {
3    // Logic
4})->middleware('check.age');

Laravel also supports terminable middleware — processing after the response has been sent to the client (e.g., logging, sending notifications).

Benefits and Use Cases

  • Separation of Concerns (SoC): Authentication, logging, and caching logic separated from business logic — cleaner code, easier maintenance.
  • Reusability: A single middleware can be used across multiple routes/controllers without code duplication.
  • Centralized Security: Authentication, authorization, and input validation at a single point instead of scattered throughout.
  • Easy Scaling: Adding/removing middleware doesn't affect core application logic.
  • Performance: Caching and compression middleware optimize response time.
  • Monitoring: Logging middleware records all requests for tracking and debugging.
Middleware Best Practices

Keep each middleware simple, doing one thing (Single Responsibility). Order correctly — CORS before Authentication before Authorization. Avoid placing business logic in middleware. Use middleware groups for easier management.

What is Laravel? The Most Popular PHP Framework

Conclusion: Middleware is an essential intermediary software layer in modern application architecture, from enterprise system integration to HTTP request processing in web frameworks. Understanding and using middleware correctly helps build secure, scalable, and maintainable applications.

Sources

Frequently Asked Questions

Frequently Asked QuestionsQ&A
What is Middleware?
Middleware is a software layer between the operating system/database and applications, helping components communicate, exchange data, and process requests efficiently.
How does Middleware work?
Middleware intercepts requests before they reach the main application, performs processing (authentication, logging, data transformation), then forwards or returns a response. This forms a middleware pipeline.
What are the types of Middleware?
Types include: Message-Oriented (MOM), Database Middleware, Application Server Middleware, API/Integration Middleware, and Web Middleware (handling HTTP requests in frameworks like Express, Laravel, Django).
What does Middleware do in REST APIs?
In REST APIs, middleware handles common tasks like JWT/OAuth authentication, logging, rate limiting, CORS, input validation, response compression, and error handling — separated from business logic.
How do you create Middleware in Laravel?
Use php artisan make:middleware MiddlewareName, write logic in the handle() method, register in bootstrap/app.php or assign directly to routes/groups. Laravel supports global, route, and group middleware.