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

使用GraphQL-codegen加载GraphQLSchema失败求助

gql-codegen执行生成操作时404+类型错误排查

问题复盘

执行gql-codegen生成代码时,出现404错误,同时抛出:

Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
at Function.entries ()

但GraphQL端点http://localhost:8000/graphql可正常访问,替换localhost为127.0.0.1后问题依旧。

排查与解决步骤

1. 检查gql-codegen配置的schema字段

  • 确认配置文件(如codegen.yml/codegen.js)中schema的URL完全正确,包括端口和路径:
    # 正确示例
    schema: "http://localhost:8000/graphql"
    
  • 如果配置了请求头(如认证),确保所有header值不为undefined或null。比如使用环境变量时,要确认变量已正确加载:
    schema:
      - http://localhost:8000/graphql:
          headers:
            Authorization: Bearer ${process.env.API_TOKEN}
    
    若API_TOKEN未设置,会导致headers对象异常,触发Object.entries错误。

2. 从终端验证端点可访问性

在执行gql-codegen的终端中,用curl直接请求端点,确认返回正常的schema数据:

curl http://localhost:8000/graphql -H "Content-Type: application/json" -d '{"query": "{ __schema { types { name } } }"}'
  • 若curl返回404:确认服务是否真的监听8000端口,本地是否有代理/防火墙拦截请求;
  • 若curl返回正常schema:问题出在gql-codegen的配置或依赖版本。

3. 升级gql-codegen相关依赖

部分旧版本的gql-codegen存在URL解析或空值处理的bug,执行升级命令:

npm update @graphql-codegen/cli @graphql-codegen/core

4. 校验配置文件格式

  • 若使用yaml配置,检查缩进、冒号等语法是否正确,避免字段拼写错误(如将schema写成scheam);
  • 若使用js配置,确保导出的配置对象没有undefined的字段,比如:
    module.exports = {
      schema: "http://localhost:8000/graphql",
      generates: {
        "./src/generated/graphql.ts": {
          plugins: ["typescript", "typescript-operations"]
        }
      }
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:41:04