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

Next.js+Hygraph博客报错:Post类型未定义excerpt字段的解决

解决Next.js+Hygraph博客文章详情页Server Error:field 'excerpt' is not defined in 'Post'

问题场景

用Next.js搭建博客,后端采用Hygraph,实现文章点击查看功能时突然触发Server Error,错误提示:

[line: 1] field 'excerpt' is not defined in 'Post'

问题定位在services/index.js的getPostDetails函数中,由GraphQL API请求代码导致。

原因分析

参考的教程版本较旧,Hygraph的GraphQL API已更新,原教程中使用的excerpt字段已从Post模型中移除或重命名,字段不匹配触发查询错误。

解决方案

  1. 打开Hygraph后台的API Playground,查看当前Post模型的所有可用字段;
  2. 对照Playground中的字段结构,修改getPostDetails函数中的GraphQL查询语句,替换掉不存在的excerpt字段;
  3. 重新测试文章详情页功能。

代码示例

原错误代码(services/index.js)

export async function getPostDetails(slug) {
  const query = `
    query GetPostDetails($slug: String!) {
      post(where: {slug: $slug}) {
        title
        excerpt // 该字段已不存在于当前Post模型
        content {
          raw
        }
        createdAt
      }
    }
  `;

  const result = await fetch(process.env.HYGRAPH_API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${process.env.HYGRAPH_API_TOKEN}`
    },
    body: JSON.stringify({ query, variables: { slug } })
  });

  return await result.json();
}

修改后正确代码(services/index.js)

export async function getPostDetails(slug) {
  // 从Hygraph API Playground获取的最新Post字段结构
  const query = `
    query GetPostDetails($slug: String!) {
      post(where: {slug: $slug}) {
        title
        summary // 替换为当前Post模型中存在的摘要字段
        content {
          raw
        }
        createdAt
        slug
      }
    }
  `;

  const result = await fetch(process.env.HYGRAPH_API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${process.env.HYGRAPH_API_TOKEN}`
    },
    body: JSON.stringify({ query, variables: { slug } })
  });

  return await result.json();
}

错误信息展示

Server Error
[line: 1] field 'excerpt' is not defined in 'Post'

模型字段参考

Hygraph Post模型字段结构截图

内容的提问来源于stack exchange,提问作者Devious

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:45:16