You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo Client 2 + React:GraphQL查询返回null问题求助

解决GraphQL查询author返回null的问题

你遇到的问题根源在于resolver的写法错误——GraphQL的resolver字段必须是一个函数,而不是直接返回对象。

看你的代码,你把Query下的author直接赋值成了一个对象:

const resolvers = {
  Query: {
    author: { name: 'billy' },
  },
};

但GraphQL期望resolver是一个函数,当查询被触发时,它会调用这个函数来获取对应的数据。你直接给对象的话,GraphQL无法正确处理这个字段的解析逻辑,所以最终返回了null。

修正后的代码

把author改成一个返回对象的函数就可以解决问题了:

import { makeExecutableSchema } from 'graphql-tools';
const typeDefs = `
type Query {
  author: Person
}
type Person {
  name: String
}
`;
const resolvers = {
  Query: {
    // 用箭头函数返回数据对象
    author: () => ({ name: 'billy' }),
  },
};
const schema = makeExecutableSchema({ typeDefs, resolvers, });
createApolloServer({ schema });

为什么这样改?

GraphQL的resolver函数会在查询执行时被调用,它的返回值就是对应字段的数据。如果是异步操作(比如从数据库读取数据),这个函数还可以返回一个Promise,GraphQL会自动等待Promise完成后再返回结果。

现在你再执行之前的查询:

query {
  author{ name }
}

就能得到正确的结果:

{ "data": { "author": { "name": "billy" } } }

内容的提问来源于stack exchange,提问作者Evanss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:01:45