首页 > 解决方案 > 尝试获取特定的单个记录时,GraphiQL 返回空值

问题描述

我正在尝试构建一个基本的 GraphQL 模式。我有一个在端口 3000 上运行的 JSON 服务器,其中包含我想使用 GraphiQL 检索的数据。

以下是我为此编写的代码:

const CustomerType = new GraphQLObjectType({
name:'Customer',
fields:() => ({
    id: { type:GraphQLString },
    name: { type:GraphQLString }        
})
});


const RootQuery = new GraphQLObjectType({
name : 'RootQueryType',
fields:{
    customer : {
        type : CustomerType,
        args:{
            id:{type:GraphQLString}
        },
        resolve(parentValue,args){
            return axios.get('http://localhost:3000/customers/?id='+args.id)
            .then(res => res.data);
        }
    }
}        
});

这就是我写查询的方式。

    customer(id : "123"){
          id,
          name
    }

这是正在生成的输出。

    {
       "data": {
          "customer": {
              "id": null,
              "name": null,
           }
       }
    }

但是,当我尝试使用 console.log 验证是否从 data.json 文件中获取正确的数据时,生成的输出包含正确的非空值。有人可以帮我解决这个问题吗?此外,当我尝试使用 GraphQLList 一次获取所有客户的列表时,也没有发生错误,如下所示:

customers:{
        type: new GraphQLList(CustomerType),
        resolve(parentValue,args){
            return axios.get('http://localhost:3000/customers/')
            .then(res => res.data);
        }

标签: node.jsgraphqlgraphql-jsjson-servergraphiql

解决方案


推荐阅读