Bad request while trying to access Github's v4 API with graphql.js

亡梦爱人 提交于 2019-12-11 04:07:05

问题


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?


回答1:


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 :

As default, GraphQL.js makes a POST request. But you can change the behavior by setting asJSON.

var graph = graphql("http://localhost:3000/graphql", {   
    asJSON: true
});

You can see the difference here

The following will work as expected :

var graph = graphql("https://api.github.com/graphql", {
  headers: {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN"
  },
  asJSON: true
});
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);
});


来源:https://stackoverflow.com/questions/48359015/bad-request-while-trying-to-access-githubs-v4-api-with-graphql-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!