我有两个不同的查询。
第一个是在私人仓库中:
const query = `{
repository(
owner: "PrivateOrg"
name: "privateRepoName"
) {
name
forkCount
forks(
first: 11
orderBy: { field: NAME, direction: DESC }
) {
totalCount
nodes {
name
}
}
}
}`
第二个是在公共仓库中。在将其放入nodeJS应用之前,我已在Explorer上对其进行了测试-它可在资源管理器上运行:
const querytwo = `{
repository(
owner: "mongodb"
name: "docs-bi-connector"
) {
name
forkCount
forks(
first: 27
orderBy: { field: NAME, direction: DESC }
) {
totalCount
nodes {
name
}
}
}
}`
除查询外,两者的取景看起来都相同:
fetch('https://api.github.com/graphql', {
method: 'POST',
body: JSON.stringify({query}),
headers: {
'Authorization': `Bearer ${accessToken}`,
},
}).then(res => res.text())
.then(body => console.log(body))
.catch(error => console.error(error));
console.log("\n\n\n");
fetch('https://api.github.com/graphql', {
method: 'POST',
body: JSON.stringify({querytwo}),
headers: {
'Authorization': `Bearer ${accessToken}`,
},
}).then(res => res.text())
.then(body => console.log(body))
.catch(error => console.error(error));
console.log("\n\n\n");
第一个查询返回:
{"data":{"repository":{"name":"mms-docs","forkCount":26,"forks":{"totalCount":8,"nodes":[{"name":"mms-docs"},{"name":"mms-docs"},{"name":"mms-docs"},{"name":"mms-docs"},{"name":"mms-docs"},{"name":"mms-docs"},{"name":"mms-docs"},{"name":"mms-docs"}]}}}}
但是第二个查询返回错误:
{"errors":[{"message":"A query attribute must be specified and must be a string."}]}
为什么会这样?
我尝试将第二个错误查询更改为在curl调用中看到的内容:
const querytwo = `query: {
repository(
owner: "mongodb"
name: "docs-bi-connector"
) {
name
forkCount
forks(
first: 27
orderBy: { field: NAME, direction: DESC }
) {
totalCount
nodes {
name
}
}
}
}`;
但是我得到同样的错误
答案 0 :(得分:0)
速记对象表示法错误
JSON.stringify({query})
是JSON.stringify({query: query})
变为
{
query:
{
repository(
owner: "PrivateOrg"
name: "privateRepoName"
) {
name
forkCount
forks(
first: 11
orderBy: { field: NAME, direction: DESC }
) {
totalCount
nodes {
name
}
}
}
}
}`
JSON.stringify({querytwo})
是JSON.stringify({querytwo: querytwo})
的简写
{
querytwo:
{
repository(
owner: "PrivateOrg"
name: "privateRepoName"
) {
name
forkCount
forks(
first: 11
orderBy: { field: NAME, direction: DESC }
) {
totalCount
nodes {
name
}
}
}
}
}`
为什么GraphQL找不到query
-它找到了queryTwo