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

按GraphQL官方教程操作报错Expected undefined to be a GraphQL schema

报错原因

你遇到的报错是因为graphql@16.x版本对graphql核心函数的传参方式做了不兼容更新,和官方文档中基于旧版本的示例代码不匹配:

  • 旧版本graphql函数支持按位置依次传入schema、query、rootValue等参数
  • 16及以上版本要求所有参数必须封装为单一对象传入,你之前按位置传参的方式导致函数读取不到正确的schema参数,因此抛出「期望得到GraphQL schema但拿到了undefined」的错误。
解决方案

方案1:修改代码适配当前graphql v16版本

将最后调用graphql函数的部分调整为对象传参格式即可,修改后的完整代码如下:

var { graphql, buildSchema } = require('graphql');

// 使用GraphQL schema语法构造schema
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// root对象为每个API端点提供解析函数
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

// 采用v16要求的对象参数格式调用
graphql({
  schema: schema,
  source: '{ hello }',
  rootValue: root
}).then((response) => {
  console.log(response);
});

修改完成后重新执行node server.js,即可正常输出结果{ data: { hello: 'Hello world!' } }。

方案2:降级graphql到v15.x版本

如果你希望直接使用官方文档的示例代码无需调整,可执行以下命令降级依赖版本:

npm install graphql@15.x --save

降级完成后运行原有代码即可正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:54:02