【发布时间】: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