Javascript 使用Graphql查询的节点获取Post请求
我试图使用GraphQL查询发出POST请求,但返回的错误是Javascript 使用Graphql查询的节点获取Post请求,javascript,node.js,express,graphql,node-fetch,Javascript,Node.js,Express,Graphql,Node Fetch,我试图使用GraphQL查询发出POST请求,但返回的错误是必须提供查询字符串,即使我的请求在PostMan中有效 以下是我如何在《邮递员》中运行它的: 下面是我在应用程序中运行的代码: const url = `http://localhost:3000/graphql`; return fetch(url, { method: 'POST', Accept: 'api_version=2', 'Content-Type': 'application/graphql'
必须提供查询字符串
,即使我的请求在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
,就像我在邮递员请求的body中指定的那样?body应该有一个query
属性,包含查询字符串。还可以传递另一个变量
属性,以便为查询提交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)
})
我创建了。感谢您共享此解决方案。但是,在第一个示例中,我必须修改
“Content-Type”:“application/graphql”
。在我的例子中,这是在标题
属性中。因此,fetch
看起来像。。。fetch(“/graphql”,{method:“POST”,标题:{“content type”:“application/json”},正文:json.stringify({query}),})