gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:28:00 25 4
gpt4 key购买 nike

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

我的 promise 没有兑现,而且总是失败。我收到代码为 400(错误请求) 的 HTTP 响应,catch 函数的 error 参数为:

{
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

我做错了什么?

最佳答案

graphql.js 的默认行为是以 form-url-encoded 格式发送正文,而 Github GraphQL api 只接受 JSON 格式。来自 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
});

你可以看出区别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);
});

关于javascript - 尝试使用 graphql.js 访问 Github 的 v4 API 时出现错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com