【问题标题】:GraphQL server not starting due to module.exports failure由于 module.exports 失败,GraphQL 服务器无法启动
【发布时间】:2022-02-20 03:22:00
【问题描述】:

我正在学习 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”部分,因为当我将其注释掉时,服务器启动时没有问题。

【问题讨论】:

  • 您能否将错误消息/堆栈跟踪添加到您的问题中?

标签: javascript node.js express graphql


【解决方案1】:

存在语法混乱。在 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 });
            }
        }
    }
});

【讨论】:

    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多