Apollo-fetch GraphQL请求

问题描述 投票:1回答:2

我是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,我收到了正确的数据。

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

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

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

graphql apollo react-apollo graphql-js
2个回答
0
投票

您的查询字符串没有关键字查询,还有一个额外的括号。它应该如下

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

0
投票

我找到的解决方案是使用普通的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));

希望它可以帮助任何有同样问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.