Why I got error: Cannot query field xx on type "Query"?

simo picture simo · May 20, 2018 · Viewed 17.7k times · Source

Although I copied and pasted the graphQL query from the GraphiQL tool after I tested it at GraphiQL successfully , the query returned with an error when I tried it in Apollo client within a reactJS app:

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

Here is my implementation:

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));

What could be wrong? here is the correct response that I expected:

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

EDIT I get expected results using GraphiQL: enter image description here

EDIT2

I tried to compare the payload between my request and GraphiQL request:

My request's payload: ( it has __typename which I don't know why )

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

GraphiQL request's payload:

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

So, they are almost identical, Any idea?

Answer

Ali Mousavi picture Ali Mousavi · Jan 9, 2020

For anyone else who might be searching for this problem, make sure you're importing ApolloClient from apollo-client package and not other packages.