Graphql 查询总是返回 null
Posted
技术标签:
【中文标题】Graphql 查询总是返回 null【英文标题】:Graphql query is always returning null 【发布时间】:2021-01-15 12:21:21 【问题描述】:我正在尝试使用 graphql 获取课程数据,但服务器总是返回 null
作为响应这是我在文件 server.js
中的代码:
var express=require('express');
const graphqlHTTP = require('express-graphql')
var buildSchema=require('graphql');
//graphql schema
var schema=buildSchema(`
type Query
course(id: Int!): Course
courses(topic:String!):[Course]
type Course
id: Int
title: String
author: String
description:String
topic:String
url: String
`);
var coursesData = [
id: 1,
title: 'The Complete Node.js Developer Course',
author: 'Andrew Mead, Rob Percival',
description: 'Learn Node.js by building real-world applications with Node, Express, MongoDB, Mocha, and more!',
topic: 'Node.js',
url: 'https://codingthesmartway.com/courses/nodejs/'
,
id: 2,
title: 'Node.js, Express & MongoDB Dev to Deployment',
author: 'Brad Traversy',
description: 'Learn by example building & deploying real-world Node.js applications from absolute scratch',
topic: 'Node.js',
url: 'https://codingthesmartway.com/courses/nodejs-express-mongodb/'
,
id: 3,
title: 'javascript: Understanding The Weird Parts',
author: 'Anthony Alicea',
description: 'An advanced JavaScript course for everyone! Scope, closures, prototypes, this, build your own framework, and more.',
topic: 'JavaScript',
url: 'https://codingthesmartway.com/courses/understand-javascript/'
]
//root resolver
var root=
course:getCourse,
courses:getCourses
;
var getCourse= function (args)
var id=args.id;
console.log("delila")
return coursesData.filter(course=>
return course.id==id
)[0]
var getCourses = function(args)
if(args.topic)
var topic=args.topic;
return coursesData.filter(course=>
course.topic===topic
);
else return coursesData
//create an experess server and graphql endpoint
var app=express();
app.use('/graphql', graphqlHTTP(
schema: schema,
rootValue:root,
graphiql:true
));
app.listen(4000,()=>console.log("delila express graphql server running on localhost 4000"))
当我去localhost:4000/graphql
获取我正在使用的数据时
query getSingleCourse($courseID: Int !)
course(id:$courseID)
title
author
description
url
topic
"courseID": 3
但我不断得到结果null
。看图
有人知道为什么会这样吗?服务器应该使用id 3
返回课程,但显然我缺少一些东西
【问题讨论】:
'args' 是第二个解析器 fn arg 【参考方案1】:您应该先定义函数表达式,然后再使用它们。就是这个原因。
与函数声明不同,JavaScript 中的函数表达式不会被提升。在创建函数表达式之前不能使用它们:
见Function expression
例如
//...
var getCourse = function (args)
var id = args.id;
console.log('delila');
return coursesData.filter((course) =>
return course.id == id;
)[0];
;
var getCourses = function (args)
if (args.topic)
var topic = args.topic;
return coursesData.filter((course) => course.topic === topic);
else return coursesData;
;
//root resolver
var root =
course: getCourse,
courses: getCourses,
;
//...
【讨论】:
以上是关于Graphql 查询总是返回 null的主要内容,如果未能解决你的问题,请参考以下文章