提供查询字符串以从GraphQL API获取 [英] Providing query string to fetch from a GraphQL API
问题描述
我正在尝试从GraphQL端点获取某些数据,但是我不断收到错误消息必须提供查询字符串".我确定我要提供查询字符串,此错误来自何处?
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?
终结点为: 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))
})
推荐答案
在这种情况下,您要使用Content-Type: 'application/json'
. application/graphql
要求整个请求都是查询,但是我不推荐这种方法,因为不可能发送查询变量.
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.
这是完整的代码示例:
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
这篇关于提供查询字符串以从GraphQL API获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!