首页 > 解决方案 > Github GraphQL 错误:必须指定查询属性并且必须是字符串

问题描述

我有两个不同的查询。

第一个是在私人仓库中:

const query = `{
  repository(
    owner: "PrivateOrg"
    name: "privateRepoName"
  ) {
    name
    forkCount
    forks(
      first: 11
      orderBy: { field: NAME, direction: DESC }
    ) {
      totalCount
      nodes {
        name
      }
    }
  }
}`

第二个是在公共回购中。在将它放入我的 nodeJS 应用程序之前,我在Explorer上对其进行了测试——它适用于 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
          }
        }
      }
    }`;

但我得到同样的错误

标签: githubgraphql

解决方案


速记对象符号错误

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


推荐阅读