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

运行GraphQL官方hello.js示例出现schema相关报错如何解决?

问题原因

你复制的是旧版官方示例代码,当前安装的是GraphQL v16及以上版本,该版本对graphql顶层调用的传参方式做了不兼容升级:旧版本支持位置参数传参,新版本要求第一个参数必须是包含schema、source等属性的配置对象,你原来的写法直接把schema作为第一个位置参数传入,函数识别不到合法的schema配置,所以抛出了"Expected undefined to be a GraphQL schema"的错误。

修复方案

两种方案二选一即可:

方案1:修改代码适配最新版本

把原来的graphql调用部分改成传对象的形式,修改后的完整hello.js代码如下:

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

var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

var root = { hello: () => 'Hello world!' };

// 调整为配置对象传参
graphql({
  schema: schema,
  source: '{ hello }',
  rootValue: root
}).then((response) => {
  console.log(response);
});

修改后重新执行node hello.js就能正常输出{ data: { hello: 'Hello world!' } }的结果。

方案2:降级GraphQL到兼容旧写法的版本

如果不想修改原有代码,可以卸载当前版本,安装v15.x的旧版本:

npm uninstall graphql
npm install graphql@15.x

安装完成后直接执行node hello.js就能正常运行原有代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:45:03