服务器 API:策略和中间件
🌐 Server API: Policies & middlewares
Page summary:就像 Strapi 核心一样,插件也可以有策略和中间件。插件策略在控制器动作之前运行,并返回
true或false来允许或阻止请求。插件中间件在整个请求/响应周期中按顺序运行,并调用next()以继续。将策略和中间件声明为工厂函数的对象,并在路由中通过插件命名空间的名称引用它们。
策略和中间件是插件服务器中拦截请求的两种机制。策略决定请求是否应该继续。中间件决定它如何被处理。
🌐 Policies and middlewares are the two mechanisms for intercepting requests in a plugin server. Policies decide whether a request should proceed. Middlewares shape how it is processed.
在深入了解本页的概念之前,请确保你已经:
🌐 Before diving deeper into the concepts on this page, please ensure you have:
- 创建了一个 Strapi 插件,
- 已阅读并理解了服务器 API的基础知识
决策指南
🌐 Decision guide
在编写任何代码之前,请使用此表选择正确的机制:
🌐 Use this table to pick the right mechanism before writing any code:
| 需求 | 机制 |
|---|---|
| 根据用户角色或状态阻止请求 | 策略 |
| 根据请求内容(body, headers)阻止请求 | 策略 或路由配置中的内联策略 |
| 当条件不满足时返回 403 | 策略 |
| 在多个路由间重用相同访问规则 | 命名 策略(已注册并通过名称引用) |
| 为插件的路由的每个响应添加头信息 | 路由级中间件 |
| 在整个服务器上记录或跟踪每个请求 | 服务器级中间件 (strapi.server.use()) |
在到达控制器之前修改 ctx.query | 路由级中间件 |
| 在多个路由间共享逻辑 | 命名 路由级中间件(已注册并通过名称引用) |
政策
🌐 Policies
策略是一个在给定路由的控制器操作之前运行的函数。它接收请求上下文,评估一个条件,并返回 true 以允许请求,或者返回 false(或抛出异常)以通过 403 响应阻止请求。
🌐 A policy is a function that runs before the controller action for a given route. It receives the request context, evaluates a condition, and returns true to allow the request or false (or throws) to block it with a 403 response.