Skip to main content

v4 代码迁移:更新全局中间件

¥v4 code migration: Updating global 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 v4 仅对全局中间件的结构进行了少量修改,允许传递额外的配置参数,而无需通过 Strapi API 手动拉入配置。

¥Strapi v4 only introduces small modifications to the structure of a global middleware, allowing for additional configuration parameters to be passed without the need to manually pull in the configuration via the Strapi API.

中间件的配置已更改(参见 配置迁移)。

¥The configuration of middlewares has changed (see configuration migration).

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 middleware converted to v4:
path: ./my-custom-packages/my-custom-middleware/lib/index.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 v3 全局中间件示例应使用以下代码转换为 Strapi v4 中间件:

¥The Strapi v3 global middleware example above should be converted to a Strapi v4 middleware using the following code:

path: ./src/middlewares/my-custom-middleware.js

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

await next();

const delta = Math.ceil(Date.now() - start);

let headerName = config.headerName || 'X-Response-Time';
ctx.set(headerName, delta + 'ms');
};
};