我正在尝试使用GraphQL查询发出POST请求,但它返回错误Must provide query string
,即使我的请求在PostMan中有效。
以下是我在PostMan中运行的方式:
这是我在我的应用程序中运行的代码:
const url = `http://localhost:3000/graphql`;
return fetch(url, {
method: 'POST',
Accept: 'api_version=2',
'Content-Type': 'application/graphql',
body: `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
任何想法我做错了什么?是否有可能使我将fetch
请求传入的body属性格式化为Text
,就像我在PostMan请求的主体中指定的一样?
答案 0 :(得分:13)
预期正文具有query
属性,其中包含查询字符串。也可以传递另一个variable
属性,以便为查询提交GraphQL变量。
这适用于您的情况:
const url = `http://localhost:3000/graphql`;
const query = `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
return fetch(url, {
method: 'POST',
Accept: 'api_version=2',
'Content-Type': 'application/graphql',
body: JSON.stringify({ query })
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
这是提交GraphQL变量的方法:
const query = `
query movies($first: Int!) {
allMovies(first: $first) {
title
}
}
`
const variables = {
first: 3
}
return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
return data
})
.catch((e) => {
console.log(e)
})