为什么我收到错误:无法在“查询”类型上查询字段 xx?

新手上路,请多包涵

虽然我在 GraphiQL 成功测试后从 GraphiQL 工具复制并粘贴了 graphQL 查询,但当我在 reactJS 应用程序的 Apollo 客户端中尝试它时,查询返回错误:

 [GraphQL error]: Message: Cannot query field "allStudents" on type "Query"., Location: [object Object], Path: undefined

这是我的实现:

 const link = createHttpLink({
  uri: 'http://localhost:8000/graphql',
  fetchOptions: { method: "POST" }
});

const client = new ApolloClient({
  link: link
});

const GET_STUDENTS = gql`
query getStudents($schoolID: Int!){
  allStudents(schoolId: $schoolID){
    pickUpLat
    pickUpLng
  }
}
`;

client
  .query({
    query: GET_STUDENTS,
    variables: { schoolID: 1 }
  })
  .then(result => console.log(result));

有什么问题?这是我期望的正确响应:

 {
  "data": {
    "allStudents": [
      {
        "pickUpLat": 31.9752942479727,
        "pickUpLng": 35.8438429235775
      },
      {
        "pickUpLat": 31.9754545979993,
        "pickUpLng": 35.8437478537235
      }
    ]
  }
}

编辑 我使用 GraphiQL 得到了预期的结果: 在此处输入图像描述

编辑2

我试图比较我的请求和 GraphiQL 请求之间的有效负载:

我的请求的有效负载:(它有 __typename 我不知道为什么)

 {"operationName":"getStudents","variables":{"schoolID":1},"query":"query getStudents($schoolID: Int) {\n  allStudents(schoolId: $schoolID) {\n    pickUpLat\n    pickUpLng\n    __typename\n  }\n}\n"}

GraphiQL 请求的负载:

 {"query":"query getStudents($schoolID: Int!){\n  allStudents(schoolId: $schoolID){\n    pickUpLat\n    pickUpLng\n  }\n}","variables":{"schoolID":1},"operationName":"getStudents"}

所以,它们几乎是相同的,知道吗?

原文由 simo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 613
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进