I am trying to retrieve some data from Github's GraphQL API using graphql.js library.
var graph = graphql("https://api.github.com/graphql", {
method: "POST",
headers: {
"Authorization": "Bearer <my-token-here>",
"Content-Type": "application/json"
},
fragments: {
rateLimitInfo: "on RateLimit {cost,remaining,resetAt}"
}
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
id
}
}
`,{
name: "freeCodeCamp",
owner: "freeCodeCamp"
}).then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
My promise is not being fulfilled and always failing. I am getting an HTTP response with code 400 (Bad Request) and the error
argument of the catch
function reads:
{
message: "Problems parsing JSON",
documentation_url: "https://developer.github.com/v3"
}
I have already tried passing the variables as JSON, like so:
{
"name": "freeCodeCamp",
"owner": "freeCodeCamp"
}
But it didn't help. I got the same bad request.
Looking at the Network tab of Chrome's inspector I see what the request payload is. Adding it here in case it give any clues or help.
query=query%20repo(%24name%3A%20String!%2C%20%24owner%3A%20String!)%7Brepository(name%3A%24name%2C%20owner%3A%24owner)%7Bid%7D%7D&variables=%7B%22name%22%3A%22freeCodeCamp%22%2C%22owner%22%3A%22freeCodeCamp%22%7D
What am I doing wrong?
The default behaviour of graphql.js is to send the body in form-url-encoded format whereas Github GraphQL api accepts only JSON format. From graphql.js readme :
You can see the difference here
The following will work as expected :