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

运行GraphQL.js官方入门代码报错Expected undefined to be a GraphQL schema

报错原因

你遇到的是graphql v16版本的不兼容变更问题,和官方文档未同步更新有关,并非你缺少依赖或者操作错误。
graphql v16对顶层graphql方法的传参规则做了破坏性调整:

  • v15及更早版本支持graphql(schema, query, rootValue, ...)多参数依次传入的写法,也就是你抄的官方示例的写法
  • v16开始仅支持传入单个配置对象作为参数,你原来的第一个入参schema被识别为配置对象,内部读取schema属性时拿到undefined,因此抛出Expected undefined to be a GraphQL schema报错。

解决方案

方案1:适配v16版本修改代码(推荐)

只需要调整你代码中graphql方法的调用写法,将多参数改为单配置对象即可,修改后的完整代码如下:

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

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

// 修改为v16支持的配置对象传参写法
graphql({
  schema: schema,
  source: '{ hello }',
  rootValue: root
}).then((response) => {
  console.log(response);
});

修改后重新执行node server.js即可正常输出结果。

方案2:降级到v15版本兼容官方示例

如果你不想修改官方示例代码,可以直接安装v15版本的graphql:

npm install graphql@15 --save

安装完成后直接运行原来的代码即可正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:15:03