问题
This question already has an answer here:
- Why does a GraphQL query return null? 1 answer
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);
}
},
On console.log(res.data)
, I am getting the data, however, on querying by date from GraphiQL, I am getting
{
"data": {
"holiday": {
"holiday": null
}
}
}
回答1:
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;
}
},
来源:https://stackoverflow.com/questions/48589649/graphql-returning-null-data-from-axios