【问题标题】:Error while returning data from Graphql endpoint从 Graphql 端点返回数据时出错
【发布时间】:2019-12-29 19:39:19
【问题描述】:

我从非常基本的 Graphql 示例开始。所以我面临的错误是

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Event.title.",
      "locations": [
        {
          "line": 34,
          "column": 5
        }
      ],
      "path": [
        "createevent",
        "title"
      ]
    }
  ],
  "data": {
    "createevent": null
  }
}

我的 graphql 端点的代码是

const express = require("express");
const bodyparser = require("body-parser");
const graphqlhttp = require("express-graphql");
const { buildSchema } = require("graphql");
const app = express();
app.use(bodyparser.json());
const events = [];
app.use(
  "/graphql",
  graphqlhttp({
    schema: buildSchema(`
    type Event {
      _id:ID!
      title:String!
      description:String!
      price:Float!
      date:String!
    }
    input Eventinput{
      title:String!
      description:String!
      price:Float!
      date:String!
    }
    type rootquery {
        events:[Event!]!

    }
    type rootmutation {
        createevent(eventinput:Eventinput):Event
    }
    schema{
        query:rootquery
        mutation:rootmutation
    }
    `),
    rootValue: {
      events: () => {
        return events;
      },
      createevent: args => {
        const event = {
          _id: Math.random().toString(),
          title: args.eventinput.title,
          description: args.eventinput.description,
          price: +args.eventinput.price,
          date: args.eventinput.date
        };
        events.push(event);
        console.log(events)
        return events
      }
    },
    graphiql: true
  })
);
app.listen(3000);

现在,当我使用 console.log(events) 时,它实际上给了我正确需要的所有值,但是在运行命令时在 localhost:3000/graphql 上

mutation {
  createevent(eventinput:{title:"Test",description:"dont",price:23.4,date:"2019-08-25T06:47:10.585Z"}){
    title
    description
  }
}

我收到了上面所说的错误,即使我已经检查了两次我无法找到问题,但是当我尝试通过以下方式获取事件时我的代码可以工作

query{
  events{
    title
    price
  }
}

只有在创建事件后我才看到上面的错误,但那东西实际上在幕后工作!!

【问题讨论】:

    标签: javascript node.js graphql


    【解决方案1】:
    events.push(event)
    console.log(events)
    return events
    

    您正在返回数组,但在您的 GraphQL 类型定义中您有

    type rootmutation {
            createevent(eventinput:Eventinput):Event
        }
    

    这表明您打算发送单个“事件”对象。对于数组,它应该是createevent(eventinput:Eventinput):[Event]。不确定它是否会完全解决您的错误,但这是问题的一部分。

    【讨论】:

    • 谢谢@Artur 它解决了我的问题我能再问你一件事吗,在突变{...}内的graphql端点中我返回标题和日期..然后在查询中(...}我获取标题和描述..这是如何工作的原因我从突变中发送标题和日期,我在查询中获取标题和描述..如果我不发送描述我如何获取它?
    • 我不确定你的意思。您是在询问查询是如何工作但突变没有工作的,还是询问为什么即使您没有对行为进行编程,查询也会返回您提供的字段?
    • 这就是 GraphQL 的重点——后端只返回您要求的字段(节省数据传输并使网站运行更快)。这是 GraphQL 本身的一个特性,它是自动的,你不需要编写任何额外的代码(除了 typedefs)
    • 我又卡在这里了,你能看看stackoverflow.com/questions/57665932/…
    猜你喜欢
    • 2019-04-22
    • 2017-11-16
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2020-05-09
    • 2023-02-11
    • 1970-01-01
    相关资源
    最近更新 更多