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

时间:2018-05-20 11:45:15

标签: reactjs graphql apollo apollo-client

虽然我在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得到了预期的结果: enter image description here

EDIT2

我尝试比较我的请求和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"}

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

3 个答案:

答案 0 :(得分:2)

我查询的错误在于我没有下载新架构。

您可以使用以下方法下载架构:apollo schema:download --endpoint=http://localhost:8080/graphql schema.json

将 http://localhost:8080/graphql 替换为您的服务器端点

您可以在https://www.apollographql.com/docs/ios/downloading-schema/

看到更多

答案 1 :(得分:1)

对于可能正在搜索此问题的其他任何人,请确保您从 ApolloClient 软件包而不是其他软件包导入 apollo-client

答案 2 :(得分:0)

对于我来说,我定义了一个不需要任何参数的查询,它将返回一个对象数组:

myBasicQuery: [BasicAnswer]

type BasicAnswer {
  name String
  phone String
}

我这样声明时遇到错误:Cannot query field \"BasicAnswer\" on type \"BasicAnswer\"

query myBasicQuery {
  BasicAnswer {
      name
      phone
  }
}

仅保留BasicAnswer的字段即可解决此问题:

query myBasicQuery {
    name
    phone
}