Apollo-fetch GraphQL 请求
Apollo-fetch GraphQL Request
我是 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,通过几乎相同的查询,我收到了正确的数据。
这是我在 postman 上使用的查询
query {
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}
我在这里做错了什么?我尝试了查询的一些变体,但结果是一样的。
您的查询字符串没有关键字query,而且还有一个额外的括号。应该是这样
fetch({
query: `
query transactions {
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}
`,
})
我找到的解决方案是使用普通 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));
希望对遇到同样问题的人有所帮助。
我是 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,通过几乎相同的查询,我收到了正确的数据。
这是我在 postman 上使用的查询
query {
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}
我在这里做错了什么?我尝试了查询的一些变体,但结果是一样的。
您的查询字符串没有关键字query,而且还有一个额外的括号。应该是这样
fetch({
query: `
query transactions {
transactions(limit: 3) {
tid
terminalNo
issuerId
}
}
`,
})
我找到的解决方案是使用普通 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));
希望对遇到同样问题的人有所帮助。