我从 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
}
}
只有在创建事件后我才会看到上面的错误,但那件事实际上在幕后工作!!
最佳答案
events.push(event)
console.log(events)
return events
您正在返回数组,但在 GraphQL typedef 中您有
type rootmutation {
createevent(eventinput:Eventinput):Event
}
这表明您打算发送单个“Event”对象。对于数组,它应该是createevent(eventinput:Eventinput):[Event]
。不确定它是否能完全解决您的错误,但它是问题的一部分。
关于javascript - 从 Graphql 端点返回数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643912/