Skip to main content

v4 代码迁移:更新配置

¥v4 code migration: Updating configuration

本指南是 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

Strapi v4 引入了多种类型的配置更改,其中包括新文件、移动或重组文件以及删除的功能。下表提供了更改的高级概述,你可以单击特定主题来阅读更多信息:

¥Strapi v4 introduces several types of changes to configurations, which includes new files, moved or restructured files, and removed features. The following table gives a high-level overview of the changes, and you can click on a specific topic to read more information:

配置主题Strapi v4 与 v3 的变化类型Strapi v4 中的文件名
数据库对现有 Strapi v3 文件的更改database.js
服务器对现有 Strapi v3 文件的更改server.js
管理面板Strapi v4 中的新文件admin.js
中间件对现有 Strapi v3 文件的更改middlewares.js
CRON 任务Strapi v4 中的新文件cron-tasks.js
API对现有 Strapi v3 文件的更改api.js
插件对现有 Strapi v3 文件的更改plugins.js
自举函数现在在全局 src/index.js 文件中定义*
自定义函数文件夹Strapi v4 中删除的功能*
自定义响应Strapi v4 中删除的功能*
✏️ 注意

代码迁移指南的这一部分并不是 Strapi v4 配置的详尽资源,这些资源在 配置文档 中进行了描述。

¥This part of the code migration guide is not an exhaustive resource for Strapi v4 configurations, which are described in the configurations documentation.

数据库配置

¥Database configuration

提醒

Strapi v4 不再支持 MongoDB 数据库。你需要迁移到 兼容的 SQL 数据库 才能使用 Strapi v4。

¥MongoDB databases are no longer supported in Strapi v4. You need to migrate to a compatible SQL database to use Strapi v4.

由于 Strapi v4 中数据库和查询层的完全重写,database.js 文件的整个结构发生了变化(请参阅 数据库配置 文档)。多数据库支持已被删除,因此不再有 defaultConnection 键。相反,在 Strapi v4 中,2 个主要数据库配置对象是:

¥Due to the complete rewrite of the database and query layers in Strapi v4, the entire structure of the database.js file has changed (see database configuration documentation). Multi-database support has been dropped, so there is no more defaultConnection key. Instead, in Strapi v4, the 2 main database configuration objects are:

  • connection,传递给数据库连接管理器包(即 Knex.js),

    ¥connection, passed to the database connection manager package (i.e. Knex.js),

  • settings 用于 Strapi 特定设置。

    ¥and settings for Strapi-specific settings.

✏️ 注意

Strapi v4 没有抽象 Knex.js 键名称,因此 Strapi v3 和 v4 中的某些键名称不同(例如 Strapi v3 中的 username 现在 Strapi v4 中的 user)(请参阅 数据库配置 文档)。

¥Strapi v4 does not abstract Knex.js key names so some key names are different in Strapi v3 and v4 (e.g. username in Strapi v3 is now user in Strapi v4) (see database configuration documentation).

Example of a Strapi v3 database configuration for PostgreSQL:
./config/database.js

module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'postgres',
host: env('DATABASE_HOST', 'localhost'),
port: env.int('DATABASE_PORT', 5432),
database: env('DATABASE_NAME', 'strapi'),
username: env('DATABASE_USERNAME', 'strapi'),
password: env('DATABASE_PASSWORD', 'strapi'),
schema: env('DATABASE_SCHEMA', 'public'), // Not Required
ssl: {
rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false), // For self-signed certificates
},
},
options: {},
},
},
});
Example of a Strapi v4 database configuration for PostgreSQL:
./config/database.js

module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
host: env('DATABASE_HOST', '127.0.0.1'),
port: env.int('DATABASE_PORT', 5432),
database: env('DATABASE_NAME', 'strapi'),
user: env('DATABASE_USERNAME', 'strapi'),
password: env('DATABASE_PASSWORD', 'strapi'),
schema: env('DATABASE_SCHEMA', 'public'), // Not Required
ssl: {
rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false), // For self-signed certificates
},
},
debug: false,
},
});

服务器配置

¥Server configuration

Strapi v4 中的 服务器配置 与 Strapi v3 类似,但有以下例外:

¥The server configuration in Strapi v4 is similar to Strapi v3, with the following exceptions:

  • 所有与管理面板相关的设置(即 admin.* 键)都在 admin.js file 中。

    ¥All admin panel-related settings (i.e. admin.* keys) are in the admin.js file.

  • CRON 任务(使用 cron.* 键配置)可以直接在 ./config/server.js 中引用或从任何其他自定义文件导入(参见 cron-tasks.js file)。

    ¥CRON tasks (configured with cron.* keys) can be directly referenced in the ./config/server.js or imported from any other custom files (see cron-tasks.js file).

  • app.keys 是重构 会话中间件 的新配置选项,用于创建安全会话密钥。

    ¥app.keys is a new configuration option for the refactored session middleware and is used to create secure session keys.

Example of a Strapi v3 server configuration:
./config/server.js

module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
admin: {
// ...
},
});
Example of a Strapi v4 server configuration:
./config/server.js

module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
app: {
keys: env.array('APP_KEYS'),
},
});

管理面板配置

¥Admin panel configuration

在 Strapi v3 中,管理面板配置是在 server.js 配置文件内的 admin 对象内定义的。

¥In Strapi v3, admin panel configuration is defined inside an admin object within the server.js configuration file.

在 Strapi v4 中,管理面板配置在 ./config/admin.js 中定义(请参阅 项目结构)。

¥In Strapi v4, the admin panel configuration is defined in ./config/admin.js (see project structure).

默认情况下,在 Strapi v4 中,admin.js 中只需要 2 个密钥:

¥By default, in Strapi v4, only 2 keys are required in admin.js:

  • apiToken.salt 用作新 API 令牌功能 的盐密钥,

    ¥apiToken.salt is used as the salt key for the new API tokens feature,

  • auth.secret(以前位于 Strapi v3 中的 server.js 文件中)用于加密管理面板的 JWT。

    ¥auth.secret (previously located in the server.js file in Strapi v3) is used to encrypt JWTs for the admin panel.

管理面板配置文档列出了所有其他 可用选项

¥The admin panel configuration documentation lists all the other available options.

Example of a Strapi v3 server.js admin configuration section:
./config/server.js

module.exports = ({ env }) => ({
// ...
admin: {
auth: {
secret: env('ADMIN_JWT_SECRET', '77b2c87dbab4e1697bec244226fbd1b3'),
},
},
});
Example of a Strapi v4 admin.js configuration file:
./config/admin.js

module.exports = ({ env }) => ({
apiToken: {
salt: env('API_TOKEN_SALT', 'd9b0df66ff97a666027e665707b4e3e7'),
},
auth: {
secret: env('ADMIN_JWT_SECRET', '77b2c87dbab4e1697bec244226fbd1b3'),
},
});

中间件配置

¥Middlewares configuration

Strapi v4 中的 中间件 已被彻底修改,并且 Strapi v3 配置格式(例如 load orderbeforeafter 键)被替换为表示加载顺序的单个数组。

¥Middlewares in Strapi v4 have been entirely overhauled and the Strapi v3 configuration format (e.g. load order, before, and after keys) is replaced with a single array representing the loading order.

Strapi v4 中的 中间件配置./config/middlewares.js 文件(复数文件名,而不是 Strapi v3 中的 middleware.js)中定义。

¥Middlewares configuration in Strapi v4 is defined in the ./config/middlewares.js file (plural file name, instead of middleware.js in Strapi v3).

Example of Strapi v3 middlewares configuration:
./config/middleware.js

module.exports = {
//...
settings: {
cors: {
origin: ['http://localhost', 'https://mysite.com', 'https://www.mysite.com'],
},
},
// ...
};
Example of Strapi v4 middlewares configuration:

重要的:需要此列表中的各种中间件。在配置期间,将字符串替换为对象格式(参见 中间件配置)。

¥Important: Various middlewares in this list are required. During configuration, replace the string with the object format (see middlewares configuration).

./config/middlewares.js

module.exports = [
'strapi::errors',
'strapi::security',
{
name: 'strapi::cors',
config: {
origin: ['http://localhost', 'https://mysite.com', 'https://www.mysite.com'],
}
},
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'strapi::session',
'strapi::favicon',
'strapi::public',
];
✏️ 注意

在 Strapi v4 中,Strapi v3 中的安全中间件已被删除并替换为 koa-helmetkoa-helmethelmet 的 Koa.js 封装器。该软件包替换了除 cors 之外的所有安全中间件(参见 内部中间件配置参考)。

¥In Strapi v4, security middlewares from Strapi v3 have been removed and replaced with koa-helmet, which is a Koa.js wrapper for helmet. This package replaces all security middlewares except for cors (see internal middlewares configuration reference).

CRON 任务

¥CRON tasks

在 Strapi v3 中,CRON 任务可以在 ./config/functions/cron.js 文件中定义。

¥In Strapi v3, CRON tasks could be defined in a ./config/functions/cron.js file.

在 Strapi v4 中,可以定义 config/functions 文件夹 不存在了CRON 任务

¥In Strapi v4, the config/functions folder does not exist anymore, and CRON tasks can be defined:

  • 在单独的文件中(例如 ./config/cron-tasks.js

    ¥in a separate file (e.g. ./config/cron-tasks.js)

  • 或者在 server.js 文件中:

    ¥or in the server.js file:

    • 要么直接在这里声明它们

      ¥either by directly declaring them here

    • 或者通过创建自定义文件并在 server.js 文件中要求它。

      ¥or by creating a custom file and requiring it in the server.js file.

API 配置

¥API configuration

Strapi v3 和 v4 中的 API 配置 选项类似,但以下键除外:

¥The API configuration options are similar in Strapi v3 and v4, with the exception of the following keys:

  • rest.defaultLimit 默认为 25(而不是 Strapi v3 中的 100

    ¥rest.defaultLimit is 25 by default (instead of 100 in Strapi v3)

  • rest.maxLimit 默认为 100(而不是 Strapi v3 中的 null

    ¥rest.maxLimit is 100 by default (instead of null in Strapi v3)

  • rest.prefix 是一个新的 API 配置选项。它的默认值为 /api,可以更改为除 / 之外的任何值。

    ¥rest.prefix is a new API configuration option. Its default value is /api and can be changed to anything but /.

API 配置是可选的。

¥The API configuration is optional.

Example of a Strapi v3 API configuration:
./config/api.js

module.exports = ({ env }) => ({
responses: {
privateAttributes: ['created_at'],
},
rest: {
defaultLimit: 100,
maxLimit: 250,
},
});
Example of a Strapi v4 API configuration:
./config/api.js

module.exports = ({ env }) => ({
responses: {
privateAttributes: ['createdAt'],
},
rest: {
prefix: '/v1',
defaultLimit: 100,
maxLimit: 250,
},
});

插件配置

¥Plugins configuration

提醒

Strapi v3 插件可能不适用于 Strapi v4。如果你是插件开发者想要将插件升级到 Strapi v4,请参阅 插件迁移指南

¥Strapi v3 plugins may not work with Strapi v4. If you are a plugin developer wanting to upgrade your plugin to Strapi v4, please refer to the plugin migration guide.

Strapi v4 中的 插件配置 包括以下功能:

¥Plugins configuration in Strapi v4 include the ability to:

  • 启用或禁用插件,

    ¥enable or disable a plugin,

  • 除了自定义配置选项之外,还具有自定义解析位置。

    ¥and have custom resolve locations in addition to custom configuration options.

要迁移到 Strapi v4,请使用新的 enabledresolve 键,并将现有 Strapi v3 自定义配置键移至嵌套 config 对象中:

¥To migrate to Strapi v4, use the new enabled and resolve keys and move existing Strapi v3 custom configuration keys into a nested config object:

Example of a Strapi v3 plugins configuration:
module.exports = ({ env }) => ({
// ...
sentry: {
dsn: env('SENTRY_DSN'),
sendMetadata: true,
},
// ...
});

Example of a Strapi v4 plugins configuration:
./config/plugins.js

module.exports = ({ env }) => ({
sentry: {
enabled: true,
resolve: './src/plugins/my-sentry-fork',
config: {
dsn: env('SENTRY_DSN'),
sendMetadata: true,
myCustomSetting: false,
},
},
graphql: {
enabled: true,
config: {
defaultLimit: 10,
maxLimit: 20,
},
},
});

✏️ 注意

具体插件配置请参考专用插件的文档。

¥For specific plugin configurations, please refer to the dedicated plugin's documentation.

自定义函数文件夹

¥Custom functions folder

Strapi v4 中不再存在 config/functions 文件夹及其所有内容。bootstrap.js 文件CRON 任务 有自己的专用配置选项,但全局功能不再自动添加到 Strapi 内部 API 中。

¥The config/functions folder and all of its content no longer exist in Strapi v4. The bootstrap.js file and CRON tasks have their own dedicated configuration options but global functions are no longer automatically added to the Strapi internal API.

在 Strapi v4 中创建通用实用函数时,建议:

¥When creating universal utility functions in Strapi v4, it's recommended to:

  • 要么创建一个专门用于保存这些实用功能的 plugin

    ¥either create a plugin dedicated to holding those utility functions,

  • 或者构建可以从 Strapi 后端的任何位置调用的 services

    ¥or build services that can be called from anywhere in the Strapi backend.

自举函数

¥Bootstrap function

专用的 bootstrap.js 文件在 Strapi v4 中不再存在,现在是与新的 register 函数结合的全局函数。bootstrap()register() 可以在 ./src/index.js 中找到(参见 函数文档)。

¥The dedicated bootstrap.js file no longer exists in Strapi v4 and is now a global function combined with the new register function. bootstrap() and register() can be found in ./src/index.js (see functions documentation).

自定义响应

¥Custom responses

由于 Strapi v4 中响应和错误处理结构的标准化,因此不再可能自定义响应结构或添加自定义响应结构。

¥Due to the standardization of the response and error handling structures in Strapi v4, it's no longer possible to customize the response structure or add custom response structures.

有关自定义错误消息,请参阅 错误处理 文档或 请求与响应 文档。

¥For custom error messages, please refer to the error handling documentation or the requests & responses documentation.

🤓 下一步

Strapi 的 迁移后端代码 到 v4 还需要至少迁移 Strapi 服务器的核心功能,例如 dependenciesroutescontrollersservices内容类型模式

¥Migrating the backend code of Strapi to v4 also requires to at least migrate the core features of the Strapi server, such as the dependencies, routes, controllers, services, and content-type schema.