GraphQL服务返回空数据求助:新手学习遇数据返回异常
GraphQL服务返回null问题排查
我是GraphQL新手,学习时遇到问题:我的GraphQL服务本该返回预设数据,但实际返回null。网上找了方案没解决,应该是漏了细节,求帮忙。

相关代码文件
index.js
import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; import { typeDefs } from "./schema.js"; import db from "./_db.js"; const resolvers = { Query:{ games(){ return db.games }, authors(){ return db.authors }, reviews(){ return db.reviews } } } //server setup const server = new ApolloServer({ //typeDefs -- definition of types of data game //resolvers -- functions that are called to get data for each field in a type' typeDefs, }) const {url} = await startStandaloneServer(server, { listen: { port: 4000 } }); console.log("Server ready at port", 4000)
schema.js
//int, float, string, boolean, ID - 5 basic scalar types export const typeDefs = `#graphql type Game{ id: ID! title: String! platform: [String]! } type Review{ id: ID! rating: Int! content: String! } type Author{ id: ID! name: String! verified: Boolean! } type Query{ reviews: [Review] games: [Game] authors: [Author] } `
_db.js
let games = [ {id: '1', title: 'Zelda, Tears of the Kingdom', platform: ['Switch']}, {id: '2', title: 'Final Fantasy 7 Remake', platform: ['PS5', 'Xbox']}, {id: '3', title: 'Elden Ring', platform: ['PS5', 'Xbox', 'PC']}, {id: '4', title: 'Mario Kart', platform: ['Switch']}, {id: '5', title: 'Pokemon Scarlet', platform: ['PS5', 'Xbox', 'PC']}, ] let authors = [ {id: '1', name: 'mario', verified: true}, {id: '2', name: 'yoshi', verified: false}, {id: '3', name: 'peach', verified: true}, ] let reviews = [ {id: '1', rating: 9, content: 'lorem ipsum', author_id: '1', game_id: '2'}, {id: '2', rating: 10, content: 'lorem ipsum', author_id: '2', game_id: '1'}, {id: '3', rating: 7, content: 'lorem ipsum', author_id: '3', game_id: '3'}, {id: '4', rating: 5, content: 'lorem ipsum', author_id: '2', game_id: '4'}, {id: '5', rating: 8, content: 'lorem ipsum', author_id: '2', game_id: '5'}, {id: '6', rating: 7, content: 'lorem ipsum', author_id: '1', game_id: '2'}, {id: '7', rating: 10, content: 'lorem ipsum', author_id: '3', game_id: '1'}, ] export default { games, authors, reviews }
问题原因及修复
创建ApolloServer实例时,未传入resolvers配置。ApolloServer需要同时接收typeDefs和resolvers才能正确处理查询,缺少resolvers的话,服务无法获取数据,就会返回null。
修改index.js里的ApolloServer初始化代码,添加resolvers参数:
const server = new ApolloServer({ typeDefs, resolvers // 新增此行 })
重启服务后再执行查询,即可拿到预设的游戏、作者和评论数据。
内容的提问来源于stack exchange,提问作者e36_King
相关产品推荐
相关产品推荐

