catandmouse
catandmouse

Reputation: 11829

Converting XHR request to axios to request data from GraphQL server

I am requesting data from GraphQLHub via XHR:

const query = '{ reddit { subreddit(name: "movies"){ newListings(limit: 2) { title comments { body author {  username commentKarma } } } } } }';

const xhr = new XMLHttpRequest(); 
xhr.open("get", 'https://www.graphqlhub.com/graphql?query=' + encodeURIComponent(query), true);
xhr.responseType = "json";
xhr.onload = () => console.log(xhr.response);
xhr.send();

This works. However I tried converting it into axios like so:

const query = '{ reddit { subreddit(name: "movies"){ newListings(limit: 2) { title comments { body author {  username commentKarma } } } } } }';

axios({
    url: "https://www.graphqlhub.com/graphql",
    method: "get",
    data: {
        query: encodeURIComponent(query)
    }
}).then((result) => {
    console.log(result.data);
});

But I am getting this error:

Uncaught (in promise) Error: Request failed with status code 400

Anything wrong with the syntax?

Upvotes: 0

Views: 1495

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84877

According to the docs:

data is the data to be sent as the request body. Only applicable for request methods 'PUT', 'POST', and 'PATCH'.

Since your method for the request is GET, the data is ignored. You should use params instead. We also don't need to encode our params, since axios already does this for us.

axios({
  url: "https://www.graphqlhub.com/graphql",
  method: "get",
  params: {
    query,
  }
})

It's probably better to just use POST instead though, since some servers don't allow mutations to be sent as GET requests.

axios({
  url: "https://www.graphqlhub.com/graphql",
  method: "get",
  data: {
    query,
  }
})

Or, better yet, just use a client like Apollo.

Upvotes: 2

Related Questions