簡體   English   中英

從Graphql端點返回數據時出錯

[英]Error while returning data from Graphql endpoint

我從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(事件)時。它實際上給了我正確需要的所有值,但在運行命令時在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
  }
}

只有在創建事件后我才會看到上面的錯誤,但那個東西實際上在幕后工作!!

events.push(event)
console.log(events)
return events

您正在返回數組,但是在您的GraphQL typedef中

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

表示您打算發送單個“事件”對象。 對於數組,它應該是createevent(eventinput:Eventinput):[Event] 不確定它是否會完全修復你的錯誤,但這是問題的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM