0

I am attempting to fetch some data from a GraphQL endpoint, however I keep getting the error "Must provide query string". I am sure I am providing the query string, where does this error come from?

The endpoint is: https://antserver-blocjgjbpw.now.sh/graphql

const query = `{
    ants {
    name
    color
    length
    weight
    }
}`

document.getElementById("basicFetchButton").addEventListener("click", () => {
	fetch("https://antserver-blocjgjbpw.now.sh/graphql", {
  	method: 'POST',
		'Content-Type': 'application/graphql',
    body: JSON.stringify({query})
  })
  .then(res => res.json())
  .then(data => console.log(data))
})

1 Answer 1

1

In this case, you want to use Content-Type: 'application/json'. application/graphql requires the entire body of the request to be the query, but I don't recommend that approach since it's impossible to send query variables.

Here's a full code sample:

fetch('https://antserver-blocjgjbpw.now.sh/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query }),
})
  .then(res => res.json())
  .then(res => console.log(res.data));

For more examples, check out my article 4 simple ways to call a GraphQL API

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.