如何使用 Strapi 插件将数据从服务器传递到管理面板
¥How to pass data from server to admin panel with a Strapi plugin
此页面的内容可能尚未与 Strapi 5 完全同步。
¥The content of this page might not be fully up-to-date with Strapi 5 yet.
Strapi 是无头的 。管理面板与服务器完全分开。
¥Strapi is headless . The admin panel is completely separate from the server.
当 开发 Strapi 插件 时,你可能希望将数据从 /server 传递到 /admin 文件夹。在 /server 文件夹中,你可以访问 Strapi 对象并可以执行数据库查询,而在 /admin 文件夹中则不能。
¥When developing a Strapi plugin you might want to pass data from the /server to the /admin folder. Within the /server folder you have access to the Strapi object and can do database queries whereas in the /admin folder you can't.
可以使用管理面板的 Axios 实例将数据从 /server 传递到 /admin 文件夹:
¥Passing data from the /server to the /admin folder can be done using the admin panel's Axios instance:
¥
要将数据从 /server 传递到 /admin 文件夹,你需要先传递 创建自定义管理路由,然后传递 获取管理面板返回的数据。
¥To pass data from the /server to /admin folder you would first create a custom admin route and then get the data returned in the admin panel.
创建自定义管理路由
¥Create a custom admin route
管理路由类似于任何控制器的路由,除了 type: 'admin' 声明将它们隐藏在通用 API 路由之外,并允许你从管理面板访问它们。
¥Admin routes are like the routes that you would have for any controller, except that the type: 'admin' declaration hides them from the general API router, and allows you to access them from the admin panel.
以下代码将为 my-plugin 插件声明自定义管理路由:
¥The following code will declare a custom admin route for the my-plugin plugin:
module.exports = {
'pass-data': {
type: 'admin',
routes: [
{
method: 'GET',
path: '/pass-data',
handler: 'myPluginContentType.index',
config: {
policies: [],
auth: false,
},
},
]
}
// ...
};
当你向 /my-plugin/pass-data URL 端点发送 GET 请求时,此路由将调用 myPluginContentType 控制器的 index 方法。
¥This route will call the index method of the myPluginContentType controller when you send a GET request to the /my-plugin/pass-data URL endpoint.
让我们创建一个基本的自定义控制器,它只返回一个简单的文本:
¥Let's create a basic custom controller that simply returns a simple text:
'use strict';
module.exports = {
async index(ctx) {
ctx.body = 'You are in the my-plugin-content-type controller!';
}
}
这意味着,当向 /my-plugin/pass-data URL 端点发送 GET 请求时,你应该获得随响应返回的 You are in the my-plugin-content-type controller! 文本。
¥This means that when sending a GET request to the /my-plugin/pass-data URL endpoint, you should get the You are in the my-plugin-content-type controller! text returned with the response.