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

Tho*_*mas 6 javascript node.js express graphql node-fetch

我正在尝试使用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);
  ...
});
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?是否有可能使我将fetch请求传入的body属性格式化为Text我在PostMan请求的主体中指定的格式?

mar*_*ani 14

期望正文具有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);
  ...
});
Run Code Online (Sandbox Code Playgroud)

这是如何提交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)
})
Run Code Online (Sandbox Code Playgroud)

在GitHub上创建了一个完整的例子.

  • 感谢您分享这个解决方案。但是,在第一个示例中,我必须修改 `'Content-Type': 'application/graphql'`。就我而言,这是在“headers”属性内。所以,“fetch”看起来像... fetch("/graphql", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query } ), }) (2认同)