【发布时间】:2020-08-05 19:49:01
【问题描述】:
我正在尝试使用 fetch 编写一个基本的 graphql 查询,该查询在使用 apollo 客户端时有效。但它不适用于 node-fetch。
类型定义如下所示:
type Query {
findLeadStat(print: PrintInput!): LeadStatWithPrint
}
input PrintInput {
printa: String!
service: String
}
type LeadStatWithPrint {
answered: Int!
printa: String!
service: String
}
这是节点获取查询:
const fetch = require('node-fetch');
( async () => {
const uri = `http://localhost:3000/graphql/v1`;
const query = `
query findLeadStat(print: PrintInput!) {
findLeadStat(print: $print){
answered
printa
service
}
}
`;
// I also tried add a query: key inside data object
const data = {
print: {
printa: "62f69234a7901e3659bf67ea2f1a758d",
service: "abc"
}
}
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({query, data})
});
console.log('and the resp: ', response);
})()
它给了我:
url: 'http://localhost:3000/graphql/v1',
status: 400,
statusText: 'Bad Request',
它适用于 Apollo GraphQL 客户端。为什么它不能与 fetch 一起使用?
因此,当我将 async await 与 node-fetch 一起使用时,响应几乎毫无用处。它只是告诉我有一个 400 错误请求错误,然后给我这个长属性对象,它们都不包含实际的错误消息。
但是当我将 fetch 调用更改为:
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables}) // same as query: query, variables: variables
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error('ERROR: ', err));
这里有两行:
.then(res => res.json())
.then(json => console.log(json))
明确了问题所在:
{
errors: [
{
message: 'Syntax Error: Expected $, found Name "fingeprint"',
locations: [Array],
extensions: [Object]
}
]
}
似乎 node-fetch 发生了两个异步事件,因此必须使用两次 await:
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables}) // same as query: query, variables: variables
})
console.log('and the resp: ', await response.json());
【问题讨论】:
标签: javascript node.js graphql