尝试使用graphql.js访问Github的v4 API时出现错误请求

时间:2018-01-20 17:23:12

标签: javascript graphql github-api graphql-js github-graphql

我正在尝试使用graphql.js库从Github的GraphQL API中检索一些数据。

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);
});

我的承诺没有实现,总是失败。我收到代码 400(错误请求)的HTTP响应,error函数的catch参数显示为:

{
    message: "Problems parsing JSON", 
    documentation_url: "https://developer.github.com/v3"
}

我已经尝试将变量作为JSON传递,如下所示:

{
    "name": "freeCodeCamp",
    "owner": "freeCodeCamp"
}

但它没有帮助。我得到了同样糟糕的要求。

查看Chrome检查器的“网络”标签,我会看到请求的有效负载是什么。如果它提供任何线索或帮助,请在此处添加。

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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

graphql.js的默认行为是以form-url编码格式发送正文,而Github GraphQL api仅接受JSON格式。来自graphql.js readme

  

默认情况下,GraphQL.js发出POST请求。但你可以改变   通过设置为JSON来实现行为。

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

您可以看到差异here

以下内容将按预期工作:

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);
});
相关问题