Skip to main content

v4 代码迁移:更新路由

¥v4 code migration: Updating routes

本指南是 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 和 v4 中,创建内容类型会自动生成核心 API 路由。

¥In both Strapi v3 and v4, creating content-types automatically generates core API routes.

在 Strapi v3 中,路由在 JSON 文件中定义,该文件导出具有 routes 属性的对象。routes 是一个对象数组,每个对象都是一个具有自己参数的路由。

¥In Strapi v3, routes are defined in JSON files that export an object with a routes property. routes is an array of objects, each object being a route with its own parameters.

在 Strapi v4 中,路由在 JavaScript 文件中定义,称为路由文件。两种类型的 v4 路由文件共存:

¥In Strapi v4, routes are defined in JavaScript files, called router files. 2 types of v4 router files coexist:

迁移 routes 取决于你想要 配置核心路由 还是 迁移自定义路由

¥Migrating routes depends on whether you want to configure core routers or migrate custom routers.

迁移核心路由

¥Migrating core routers

将核心路由迁移到 Strapi v4 包括确保每个路由文件使用 v4 中引入的 createCoreRouter 工厂功能。

¥Migrating a core router to Strapi v4 consists in making sure that each router file uses the createCoreRouter factory function introduced in v4.

由于 Strapi v3 和 v4 中的路由实现存在差异,因此需要创建一个新的路由文件,然后可以选择将现有的 Strapi v3 自定义项引入新文件中,并在必要时进行调整。

¥Due to the differences between routes implementation in Strapi v3 and v4, it's required to create a new router file, then optionally bring existing Strapi v3 customizations into the new file and adapt them when necessary.

创建 v4 核心路由文件:

¥To create a v4 core router file:

  1. ./src 文件夹内创建 api/<api-name>/routes/<router-name>.js 文件(请参阅 项目结构)。

    ¥Create a api/<api-name>/routes/<router-name>.js file inside the ./src folder (see project structure).

  2. 将以下代码复制并粘贴到 ./src/api/<api-name>/routes/<router-name>.js 文件的顶部。该代码从 Strapi 核心包含的工厂导入 createCoreRouter 工厂函数:

    ¥Copy and paste the following code at the top of the ./src/api/<api-name>/routes/<router-name>.js file. The code imports the createCoreRouter factory function from the factories included with the core of Strapi:

    const { createCoreRouter } = require('@strapi/strapi').factories;
  3. 复制并粘贴以下代码,将 api-namecontent-type-name 替换为适当的名称。该代码导出对 createCoreRouter 工厂函数的调用结果,并将内容类型的唯一标识符(例如 api::api-name.content-type-name)作为参数传递:

    ¥Copy and paste the following code, replacing api-name and content-type-name with appropriate names. The code exports the result of a call to the createCoreRouter factory function, passing the unique identifier of the content-type (e.g. api::api-name.content-type-name) as an argument:

    module.exports = createCoreRouter('api::api-name.content-type-name')
  4. (可选)要配置路由,请将第二个参数传递给 createCoreRouter 工厂函数。该参数可以是一个对象,也可以是一个返回对象的函数。该对象包含方法,这些方法可以是全新的操作,也可以替换或扩展核心 API 路由的现有操作(请参阅 路由实现文档)。

    ¥(optional) To configure the router, pass a second argument to the createCoreRouter factory function. This argument can be either an object or a function returning an object. The object contains methods, which can either be entirely new actions or replace or extend existing actions of core API routes (see routes implementation documentation).

Example of a Strapi v4 core router without customization:
./src/api/<content-type-name>/routes/<router-name>.js

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::api-name.content-type-name');
Example of a Strapi v4 core router with customization:
./src/api/<content-type-name>/routes/<router-name>.js

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::api-name.content-type-name', {
// creates an object with the basic CRUD configuration
// ...
config: {
find: {
// disables authorization requirement for the `find` route
policies: ['admin::isAuthenticatedAdmin'],
// here you can also customize auth & middlewares
},
},
// disables every action except `find` and `findOne`.
only: ['find', 'findOne'],
});

迁移自定义路由

¥Migrating custom routers

Strapi v4 中的自定义路由是导出对象数组的 JavaScript 文件,每个对象都是一条路由,其结构类似于 Strapi v3 中使用的 JSON 路由配置文件。

¥Custom routers in Strapi v4 are JavaScript files that export an array of objects, each object being a route, in a structure similar to the JSON routers configuration files used in Strapi v3.

要将自定义路由迁移到 Strapi v4:

¥To migrate a custom router to Strapi v4:

  1. ./src 文件夹内创建 api/<api-name>/routes/<custom-router-name>.js 文件(请参阅 项目结构)。

    ¥Create a api/<api-name>/routes/<custom-router-name>.js file inside the ./src folder (see project structure).

  2. 确保此 ./src/api/<api-name>/routes/<custom-router-name>.js 文件导出一个对象:

    ¥Make sure this ./src/api/<api-name>/routes/<custom-router-name>.js file exports an object:

    ./src/api/<api-name>/routes/<router-name>.js

    module.exports = {

    }
  3. 将 Strapi v3 JSON 文件中声明的 routes 数组复制并粘贴到 Strapi v4 文件导出的对象中。

    ¥Copy and paste the routes array declared in the Strapi v3 JSON file into the object exported by the Strapi v4 file.

  4. 将 Strapi v4 中导出的对象转换为更清晰的 JavaScript 格式,从 Strapi v3 JSON 格式中删除键上的所有 "(例如 "method"method"path"path)。

    ¥Convert the exported object in Strapi v4 to a cleaner JavaScript format, removing all " on keys from the Strapi v3 JSON format (e.g. "method"method, "path"path).

Example of a Strapi v4 custom router:
./src/api/restaurant/routes/custom-restaurant.js

module.exports = {
routes: [
{ // Path defined with a URL parameter
method: 'GET',
path: '/restaurants/:category/:id',
handler: 'Restaurant.findOneByCategory',
},
{ // Path defined with a regular expression
method: 'GET',
path: '/restaurants/:region(\\d{2}|\\d{3})/:id', // Only match when the first parameter contains 2 or 3 digits.
handler: 'Restaurant.findOneByRegion',
},
{ // Route with custom policies
method: 'POST',
path: "/restaurants/:id/reservation",
handler: 'Restaurant.reservation',
config: {
policies: ["is-authenticated", "has-credit-card"]
}
}
]
}

🤓 下一步

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

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