Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Graphql查询的节点获取Post请求_Javascript_Node.js_Express_Graphql_Node Fetch - Fatal编程技术网

Javascript 使用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'

我试图使用GraphQL查询发出POST请求,但返回的错误是
必须提供查询字符串
,即使我的请求在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}),})