使用Gatsby GraphQL无法从Strapi获取图片数据的问题
问题描述
我正在使用Strapi v4、Gatsby v4.23.0以及gatsby-source-strapi v2。我的gatsby-config.js配置如下:
const strapiConfig = { apiURL: process.env.STRAPI_API_URL, accessToken: process.env.STRAPI_TOKEN, collectionTypes: [ { singularName: 'article', queryParams: { // Populate media and relations // Make sure to not specify the fields key so the api always returns the updatedAt populate: { 'articleSection': { image: { populate: { data: "*" } }, images: "*", }, 'categories': "*" }, }, }, { singularName: 'category', }, ], singleTypes: [], }
在Strapi中,Article数据模型结构如下:
我在Strapi GraphQL中可以查看图片数据,但在Gatsby GraphQL explorer中却看不到这些数据,显示内容如下:
请问如何获取图片数据?
解决方法
调整填充规则适配Strapi v4结构
Strapi v4的媒体字段嵌套层级是data.attributes,你当前的data: "*"无法完整取出图片属性。修改gatsby-config.js中的填充配置,直接对媒体字段使用populate: "*":populate: { 'articleSection': { image: { populate: "*" }, images: { populate: "*" }, }, 'categories': "*" }清理Gatsby缓存后重新构建
Gatsby会缓存旧数据,配置修改后需清理缓存生效:gatsby clean && gatsby develop检查Strapi权限配置
确保你的API令牌拥有访问媒体库、Article集合的find权限,在Strapi后台设置→角色与权限中确认对应角色的权限已开启。验证Strapi API返回数据
直接访问Strapi接口(如${STRAPI_API_URL}/api/articles?populate=deep),确认返回的JSON中包含articleSection.image的完整属性数据,排除Strapi端的数据返回问题。确认插件版本兼容性
检查gatsby-source-strapiv2是否完全适配Strapi v4,必要时升级到官方推荐的兼容版本。
内容的提问来源于stack exchange,提问作者davideghz
相关产品推荐
相关产品推荐

