如何解决Graphql查询始终返回null
我正在尝试使用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',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
}
有人知道为什么会这样吗?服务器应返回id 3
的课程,但显然我缺少某些内容
解决方法
您应该先定义函数表达式,然后再使用它们。这就是原因。
与函数声明不同,不会悬挂JavaScript中的函数表达式。创建函数表达式之前,不能使用它们:
例如
//...
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,};
//...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。