由于 module.exports 故障,GraphQL 服务器未启动
GraphQL server not starting due to module.exports failure
我正在学习 GraphQL,但在尝试启动服务器时遇到了错误。
const graphql = require('graphql');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema
} = graphql;
const Users = [
{ id: '23', firstName: 'Bill', age: 20 },
{ id: '41', firstName: 'Jane', age: 18 }
];
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLString },
firstName: { type: GraphQLString },
age: { type: GraphQLInt }
}
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(Users, { id: args.id });
}
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
server.js代码在这里:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema/schema');
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
app.listen(4000, () => {
console.log("Server running at port 4000.");
});
错误似乎来自“module.exports”部分,因为当我将其注释掉时,服务器启动没有问题。
语法混乱。 RootQuery中user下的type部分完全覆盖了整个字段结构,错误就在这里。
只需删除顶级 type: {}
。
试试这个:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(Users, { id: args.id });
}
}
}
});
我正在学习 GraphQL,但在尝试启动服务器时遇到了错误。
const graphql = require('graphql');
const _ = require('lodash');
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema
} = graphql;
const Users = [
{ id: '23', firstName: 'Bill', age: 20 },
{ id: '41', firstName: 'Jane', age: 18 }
];
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLString },
firstName: { type: GraphQLString },
age: { type: GraphQLInt }
}
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(Users, { id: args.id });
}
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
server.js代码在这里:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema/schema');
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
app.listen(4000, () => {
console.log("Server running at port 4000.");
});
错误似乎来自“module.exports”部分,因为当我将其注释掉时,服务器启动没有问题。
语法混乱。 RootQuery中user下的type部分完全覆盖了整个字段结构,错误就在这里。
只需删除顶级 type: {}
。
试试这个:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: { id: { type: GraphQLString } },
resolve(parentValue, args) {
return _.find(Users, { id: args.id });
}
}
}
});