2

我正在尝试使用 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

我究竟做错了什么?

4

1 回答 1

1

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

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

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

你可以在这里看到区别

以下将按预期工作:

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);
});
于 2018-01-26T19:10:45.877 回答