Skip to main content

v4 代码迁移:更新路由中间件

¥v4 code migration: Updating route middlewares

本指南是 v4 代码迁移指南 的一部分,旨在帮助你将 Strapi 应用的代码从 v3.6.x 迁移到 v4.0.x

¥This guide is part of the v4 code migration guide designed to help you migrate the code of a Strapi application from v3.6.x to v4.0.x

🤓 v3/v4 比较

在 Strapi v3 中,策略还用作路由中间件来更改请求或响应负载,或者用额外的逻辑封装控制器。

¥In Strapi v3, policies are also used as route middlewares to make changes to the request or response payload or to wrap a controller with extra logic.

在 Strapi v4 中,用于授权和验证的 policies 和用于额外逻辑、封装和定制的 middlewares 之间有明显的区别。

¥In Strapi v4, there is a clear distinction between policies, which are used for authorization and validation, and middlewares, which are used for extra logic, wrapping, and customization.

充当中间件的 Strapi v3 策略应通过创建新的中间件来转换为 Strapi v4 中的 路由中间件。不充当路由中间件的 Strapi v3 策略应使用 政策迁移文档 迁移到 v4。

¥A Strapi v3 policy acting as a middleware should be converted to a route middleware in Strapi v4 by creating a new middleware. Strapi v3 policies not acting as route middlewares should be migrated to v4 using the policies migration documentation.

strapi generate 交互式 CLI 是创建新中间件的推荐方法:

¥The strapi generate interactive CLI is the recommended way to create a new middleware:

  1. 在终端中运行 yarn strapi generate

    ¥Run yarn strapi generate in a terminal.

  2. 使用交互式 CLI,选择中间件应应用的位置并为其命名。

    ¥Using the interactive CLI, choose where the middleware should apply and give it a name.

  3. 将自定义添加到生成的文件中。

    ¥Add customizations to the generated file.

Example of a Strapi v3 policy converted to a Strapi v4 middleware

以下 Strapi v3 策略充当中间件:

¥The following Strapi v3 policy acts as a middleware:

path: ./api/api-name/config/policies/my-policy.js

module.exports = async (ctx, next) => {
const start = Date.now();

await next();

const delta = Math.ceil(Date.now() - start);
ctx.set('X-Response-Time', delta + 'ms');
};

应使用以下代码将其转换为 Strapi v4 中间件:

¥It should be converted to a Strapi v4 middleware using the following code:

path: ./src/api/api-name/middlewares/my-middleware.js

module.exports = (config, { strapi }) => {
return async (ctx, next) => {
const start = Date.now();

await next();

const delta = Math.ceil(Date.now() - start);
ctx.set('X-Response-Time', delta + 'ms');
};
};