【问题标题】:GraphQL Tutorial - Expected undefined to be a GraphQL schemaGraphQL 教程 - 预期未定义为 GraphQL 模式
【发布时间】:2021-12-23 16:25:26
【问题描述】:

我尝试学习 GraphQL。我创建了一个项目,我按照this page 所说的做了。

安装

   npm init
   npm install graphql --save

Server.js

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!';
  },
};

// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

运行

node server.js

这会返回一个错误。

    throw new Error(
          ^
Error: Expected undefined to be a GraphQL schema.
    at assertSchema (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\type\schema.js:35:11)
    at validateSchema (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\type\validate.js:34:28)
    at graphqlImpl (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:52:64)
    at C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:21:43
    at new Promise (<anonymous>)
    at graphql (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:21:10)
    at Object.<anonymous> (C:\Users\BK\Projects\Test\graphql-test\server.js:18:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)

版本

  • graphql:“^16.0.1”
  • 节点:v16.13.0

【问题讨论】:

  • 遗憾的是,我认为这个教程错过了 GraphQL 的要点:/ 移到下一页它变得更加现实。但在初学者级别,目标是减少使用 root 值,而更多地使用 resolvers,这更接近于您将来真正构建模式的方式。

标签: node.js graphql graphql-js


【解决方案1】:

我按照相同的教程进行操作,但遇到了同样的问题。转到下一页后,正如 U Rogel 建议的那样,我遇到了以下问题:

Could not resolve dependency:
npm ERR! peer graphql@"^14.7.0 || ^15.3.0" from express-graphql@0.12.0
npm ERR! node_modules/express-graphql

所以,我决定在package.json修改我的graphql版本:

"dependencies": {
    "express": "^4.17.1",
    "express-graphql": "^0.12.0",
    "graphql": "^14.7.0"
}

然后我运行npm install,回到第一页,它成功了!
我认为问题在于版本 16+ 不适用于基本示例。

【讨论】:

  • 感谢您的回复。但我不再关注这个网站。相反,我参加了Apollo GraphQL。我也推荐给你,非常通俗易懂。
猜你喜欢
  • 2021-12-15
  • 2020-06-01
  • 1970-01-01
  • 2021-03-17
  • 2019-04-11
  • 2019-10-01
  • 2019-10-06
  • 2018-11-09
  • 2019-01-22
相关资源
最近更新 更多