Providing query string to fetch from a GraphQL API

2019-08-18 05:10发布

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条回答
该账号已被封号
2楼-- · 2019-08-18 05:53

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

查看更多
登录 后发表回答