You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Strapi自定义插件中访问后台面板内容类型数据?

Strapi自定义插件中访问内置内容类型的正确方法

1. 优先使用Strapi内部服务(无权限问题)

插件运行在Strapi后端环境中,直接调用内部服务层获取数据,无需走HTTP接口,也就不会触发401权限校验。

  • 获取用户数据(用户权限插件内置的user内容类型):
// 在插件的控制器或服务文件中
const users = await strapi.service('plugin::users-permissions.user').find({
  // 可按需添加过滤、排序参数
  filters: { isActive: true },
  sort: { createdAt: 'desc' }
});
  • 获取自定义分类数据(项目内的api::category.category内容类型):
const categories = await strapi.service('api::category.category').find({});

注意:服务的命名规则为 plugin::[插件标识].[内容类型名](内置用户插件标识是users-permissions),项目自定义内容类型则是 api::[内容类型名].[内容类型名]。

2. 若需走HTTP接口,配置权限并携带令牌

如果必须通过外部API接口(如/api/users)访问,需完成两步配置:

  • 后台权限配置:进入「设置」→「角色与权限」,找到对应角色(如Authenticated),开启users-permissions插件下user内容类型的find/findOne权限,同时配置category内容类型的对应权限。
  • 请求携带令牌:插件内的前端代码调用接口时,需从后台会话中获取有效的JWT令牌,放在请求头的Authorization字段中:
// 插件前端代码示例
const token = strapi.auth.getToken();
const response = await fetch('/api/users', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});
const users = await response.json();

3. 关联内容类型的正确配置

在插件的Articles内容类型schema中,需正确指定关联目标的UID,这样查询Articles时可直接关联获取用户/分类数据:

// 插件路径:src/plugins/your-plugin/content-types/article/schema.json
{
  "attributes": {
    "author": {
      "type": "relation",
      "relation": "manyToOne",
      "target": "plugin::users-permissions.user"
    },
    "category": {
      "type": "relation",
      "relation": "manyToOne",
      "target": "api::category.category"
    }
  }
}

查询Articles时通过populate关联加载:

const articles = await strapi.service('plugin::your-plugin.article').find({
  populate: ['author', 'category']
});

内容的提问来源于stack exchange,提问作者Shiv Shankar Prasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 10:32:33