Skip to main content

后端自定义

Page summary:

Strapi 的后端是一个基于 Koa 的服务器,请求会通过全局中间件、路由、控制器、服务和模型,然后 Document 服务才返回响应。

Disambiguation: Strapi back end

作为一个无头 CMS,Strapi 软件整体上可以被视为你网站或应用的“后端”。 但 Strapi 软件本身包含两个不同的部分:

🌐 As a headless CMS, the Strapi software as a whole can be considered as the "back end" of your website or application. But the Strapi software itself includes 2 different parts:

  • Strapi 的 后端 部分是 Strapi 运行的一个 HTTP 服务器。像任何 HTTP 服务器一样,Strapi 后端接收请求并发送响应。你的内容存储在数据库中,Strapi 后端与数据库交互以创建、检索、更新和删除内容。
  • Strapi 的 前端 部分称为管理面板。管理面板提供图形用户界面,帮助你组织和管理内容。

在整个开发者文档中,“后端”专指 Strapi 的后端部分。

🌐 Throughout this developer documentation, 'back end' refers exclusively to the back-end part of Strapi.

入门 > 管理员面板页面 提供了管理员面板的概览,管理员面板自定义部分 详细说明了管理员面板可用的各种自定义选项。

🌐 The Getting Started > Admin panel page gives an admin panel overview and the admin panel customization section details the various customization options available for the admin panel.

Strapi 后端运行一个基于 Koa 的 HTTP 服务器, Koa 是一个后端 JavaScript 框架。

像任何 HTTP 服务器一样,Strapi 后端接收请求并发送响应。你可以通过 RESTGraphQL API 向 Strapi 后端发送请求,以创建、检索、更新或删除数据。

🌐 Like any HTTP server, the Strapi back end receives requests and send responses. You can send requests to the Strapi back end to create, retrieve, update, or delete data through the REST or GraphQL APIs.

请求可以通过 Strapi 后端传输,如下所示:

🌐 A request can travel through the Strapi back end as follows:

  1. Strapi 服务器接收一个 请求
  2. 请求会触发按顺序运行的全局中间件
  3. 该请求访问了一个路由
    默认情况下,Strapi 会为你创建的所有内容类型生成路由文件(参见REST API 文档),并且可以添加和配置更多路由。
  4. 路由策略 充当只读的验证步骤,可以阻止访问某条路由。路由中间件 可以控制请求流程,并在继续之前修改请求本身。
  5. 控制器 在路由被访问后执行代码。服务 是可选的附加代码,可用于构建可被控制器重复使用的自定义逻辑。
  6. 控制器和服务执行的代码与模型交互,这些模型是存储在数据库中的内容结构的表示形式。
    通过模型表示的数据的交互由文档服务查询引擎处理。
  7. 你可以实现 文档服务中间件 来在数据发送到查询引擎之前进行控制。查询引擎也可以使用生命周期钩子,不过我们建议你使用文档服务中间件,除非你确实需要直接与数据库交互。
  8. 服务器返回一个 响应。响应可以在发送之前通过路由中间件和全局中间件返回。

全局和路由中间件都包含一个异步回调函数 await next()。根据中间件返回的内容,请求将在后端走一条较短或较长的路径:

🌐 Both global and route middlewares include an asynchronous callback function, await next(). Depending on what is returned by the middleware, the request will either go through a shorter or longer path through the back end:

  • 如果中间件不返回任何内容,则请求将继续穿过后端的各个核心元素(即控制器、服务以及与数据库交互的其他层)。
  • 如果中间件在调用 await next() 之前返回,将会立即发送响应,跳过其余的核心元素。然后,它将沿着原路返回同一条链。
Info

请注意,本节页面中描述的所有自定义仅适用于 REST API。GraphQL 自定义 在 GraphQL 插件文档中描述。

🌐 Please note that all customizations described in the pages of this section are only for the REST API. GraphQL customizations are described in the GraphQL plugin documentation.

交互式图表

🌐 Interactive diagram

下图展示了请求如何通过 Strapi 后端传输。你可以点击任意形状跳转到文档中的相关页面。

🌐 The following diagram represents how requests travel through the Strapi back end. You can click on any shape to jump to the relevant page in the documentation.

Loading diagram...