节点使用Graphql查询获取发布请求

时间:2017-06-17 23:22:14

标签: javascript node.js express graphql node-fetch

我正在尝试使用GraphQL查询发出POST请求,但它返回错误Must provide query string,即使我的请求在PostMan中有效。

以下是我在PostMan中运行的方式:

enter image description here

enter image description here

这是我在我的应用程序中运行的代码:

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请求的主体中指定的一样?

1 个答案:

答案 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)
})

我创建了a complete example on GitHub

相关问题