Javascript 尝试访问Github';时请求错误;带graphql.js的v4 API
我试图使用GraphQL.js库从Github的GraphQLAPI检索一些数据Javascript 尝试访问Github';时请求错误;带graphql.js的v4 API,javascript,graphql,github-api,graphql-js,github-graphql,Javascript,Graphql,Github Api,Graphql Js,Github Graphql,我试图使用GraphQL.js库从Github的GraphQLAPI检索一些数据 var graph = graphql("https://api.github.com/graphql", { method: "POST", headers: { "Authorization": "Bearer <my-token-here>", "Content-Type": "application/json" }, fragments: { rateLi
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);
});
我已经尝试过将变量作为JSON传递,如下所示:
{
"name": "freeCodeCamp",
"owner": "freeCodeCamp"
}
但这没用。我也收到了同样糟糕的要求
查看Chrome inspector的网络选项卡,我看到了请求负载是什么。在这里添加,以防提供任何线索或帮助
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
我做错了什么?的默认行为是以url编码格式发送正文,而Github GraphQL api只接受JSON格式。发件人:
默认情况下,GraphQL.js发出POST请求。但是你可以改变你的想法
通过设置为json来实现行为
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);
});
graphql.js形成数据有效负载的形式似乎不是Github API所期望的格式。我尝试从html文件运行代码,但似乎不起作用。维护GraphQL.js的人员没有响应。知道为什么会失败吗?
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);
});