提供查询字符串以从 GraphQL 获取 API
Providing query string to fetch from a GraphQL API
我正在尝试从 GraphQL 端点获取一些数据,但我一直收到错误 "Must provide query string"。我确定我提供了查询字符串,这个错误是从哪里来的?
终点是: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
要求整个请求体都是查询,但我不推荐这种方法,因为它不可能发送查询变量。
这是完整的代码示例:
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));
更多示例,请查看我的文章4 simple ways to call a GraphQL API
我正在尝试从 GraphQL 端点获取一些数据,但我一直收到错误 "Must provide query string"。我确定我提供了查询字符串,这个错误是从哪里来的?
终点是: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
要求整个请求体都是查询,但我不推荐这种方法,因为它不可能发送查询变量。
这是完整的代码示例:
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));
更多示例,请查看我的文章4 simple ways to call a GraphQL API