GraphQL从axios返回空数据 [英] GraphQL returning null data from axios
问题描述
我正在用Node.js和Express编写GraphQL服务器.我有一个JSON数据文件,因此我正在使用Axios从该JSON文件查询数据并将其传递给GraphQL查询,
I am writing a GraphQL server in Node.js and Express. I have a JSON file of data and so I am using Axios to query data from that JSON file and pass it to GraphQL query,
const RootQuery = new GraphQLObjectType({
name:'RootQueryType',
fields: {
holiday: {
type: Holiday,
args:{
date:{type:GraphQLString},
},
resolve(parentValue, args) {
return axios.get('http://localhost:3000/holidays?date='+ args.date).then(res => res.data);
}
},
在console.log(res.data)
上,我正在获取数据,但是,在从GraphiQL中按日期查询时,我正在获取
On console.log(res.data)
, I am getting the data, however, on querying by date from GraphiQL, I am getting
{
"data": {
"holiday": {
"holiday": null
}
}
}
{
"data": {
"holiday": {
"holiday": null
}
}
}
推荐答案
有时我遇到了完全相同的问题.我意识到从REST API/JSON文件中获取数据需要一些时间,而GraphQL并没有等待接收它.因此,我决定使用Async和Await,这样GraphQL就等待接收数据.在您的情况下,代码如下所示:
I struggled with the exact same issue sometime back. I realized that the data from the REST API / JSON file take some time to be fetched and GraphQL doesn't wait to receive it. So I decided to use Async and Await, and that way, GraphQL waited for the data to be received. In your case, the code would look like:
const RootQuery = new GraphQLObjectType({
name:'RootQueryType',
fields: {
holiday: {
type: Holiday,
args:{
date:{type:GraphQLString},
},
Async resolve(parentValue, args) {
const results= await axios.get('http://localhost:3000/holidays?date='+ args.date)
.then(res => res.data);
return results;
}
},
这篇关于GraphQL从axios返回空数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!