尝试使用graphql.js访问Github的v4 API时请求错误 [英] Bad request while trying to access Github's v4 API with graphql.js
问题描述
我正在尝试使用graphql.js库从Github的GraphQL API中检索一些数据.
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);
});
我的诺言没有兑现,而且总是失败.我收到代码为 400(错误请求)的HTTP响应,并且catch
函数的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"
}
我已经尝试过将变量作为JSON传递,就像这样:
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.
在Chrome检查器的网络"标签上,我看到了请求有效载荷是什么.如果有任何提示或帮助,请在此处添加.
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
我在做什么错了?
推荐答案
graphql.js的默认行为用于以表单网址编码格式发送正文,而Github GraphQL api仅接受JSON格式.来自 graphql.js自述文件:
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 :
默认情况下,GraphQL.js发出POST请求.但是你可以改变 通过设置asJSON来实现行为.
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
});
您可以在此处
以下将按预期工作:
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的v4 API时请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!