【问题标题】:Providing query string to fetch from a GraphQL API提供查询字符串以从 GraphQL API 中获取
【发布时间】:2018-05-24 07:14:23
【问题描述】:

我正在尝试从 GraphQL 端点获取一些数据,但是我不断收到错误消息“必须提供查询字符串”。我确定我提供了查询字符串,这个错误来自哪里?

端点是:https://antserver-blocjgjbpw.now.sh/graphql

const query = `{
    ants {
    name
    color
    length
    weight
    }
}`

document.getElementById("basicFetchButton").addEventListener("click", () => {
	fetch("https://antserver-blocjgjbpw.now.sh/graphql", {
  	method: 'POST',
		'Content-Type': 'application/graphql',
    body: JSON.stringify({query})
  })
  .then(res => res.json())
  .then(data => console.log(data))
})

【问题讨论】:

    标签: fetch graphql endpoint


    【解决方案1】:

    在这种情况下,您想使用Content-Type: 'application/json'application/graphql 要求请求的整个主体都是查询,但我不推荐这种方法,因为不可能发送查询变量。

    这是一个完整的代码示例:

    fetch('https://antserver-blocjgjbpw.now.sh/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query }),
    })
      .then(res => res.json())
      .then(res => console.log(res.data));
    

    更多示例,请查看我的文章4 simple ways to call a GraphQL API

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 2018-12-30
      • 2019-06-09
      • 2019-06-02
      • 2016-08-10
      • 2011-08-30
      • 2013-05-16
      • 2022-01-18
      • 2021-05-24
      相关资源
      最近更新 更多