【问题标题】:Apollo-fetch GraphQL RequestApollo-fetch GraphQL 请求
【发布时间】:2019-07-26 09:16:24
【问题描述】:

我对 GraphQL 很陌生,我正在努力从前端的 API 中获取数据。

我正在使用apollo-fetch 构建查询并发出请求,即

const fetch = createApolloFetch({
  uri: `${BASE_API_URL}/graphql`,
});
fetch({
  query: `{
    transactions(limit: 3) {
      tid
      terminalNo
      issuerId
    }
  }`,
}).then(res => {
  console.log('res', res);
}).catch(err => console.log(err));

我收到此错误:"Syntax Error: Expected Name, found String "query""

奇怪的是,使用 Postman,通过几乎相同的查询,我收到了正确的数据。

这是我在邮递员上使用的查询

query {
  transactions(limit: 3) {
   tid
   terminalNo
   issuerId
 }
}

我在这里做错了什么?我尝试了查询的一些变体,但结果是一样的。

【问题讨论】:

    标签: graphql apollo react-apollo graphql-js


    【解决方案1】:

    您的查询字符串没有关键字查询,并且还有一个额外的括号。应该是这样的

    fetch({
      query: `
       query transactions {
         transactions(limit: 3) {
          tid
          terminalNo
          issuerId
         }
        }
    `,
    })
    

    【讨论】:

    • 同样的结果。这是我的第一次尝试。不是逗号。
    • 我已经更正了答案。我的坏没有注意到你的查询字符串
    • 还是同样的问题
    【解决方案2】:

    我找到的解决方案是使用纯 javascript,尚不确定 apollo-fetch 出现错误的原因

    fetch(`${BASE_API_URL}/graphql`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: `query {
        transactions(limit: 3, offset: 0) {
          tid
          terminalNo
          issuerId
        } 
      }`,
    })
    .then(res => res.json())
    .then(res => (
      this.setState({ transactions: res.data.transactions })
    ))
    .catch(error => console.log('error', error));
    

    希望对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 2018-11-02
      • 2020-10-13
      • 2018-10-21
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2021-11-22
      相关资源
      最近更新 更多