You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

GraphQL请求报错:无法在Query类型上查询repository字段求助

解决GraphQL请求GitHub API时的"Cannot query field 'repository' on type 'Query'"错误

嘿,这种在GraphiQL里跑的好好的,一到Node代码里就报错的情况我见得多了,大概率是请求配置出了问题,咱们一步步来排查解决:

1. 先确认API端点是不是用错了

GitHub GraphQL API的正确地址是 https://api.github.com/graphql,很多人会不小心把它和REST API的端点搞混,或者用了旧的测试地址,这是最容易踩的坑。你得确保在graphql-request里请求的是这个正确端点。

2. 检查认证是否到位

GitHub的GraphQL API几乎所有操作都需要认证——哪怕你查的是公共仓库的issues,没带token的话不仅请求限制极低,还可能导致API返回的schema里不包含repository字段(未认证状态下部分字段会被隐藏)。你在GraphiQL里登录了,所以自动带上了认证信息,但Node代码里得手动加:

const { request } = require('graphql-request');

// 正确的端点
const endpoint = 'https://api.github.com/graphql';
// 去GitHub设置里生成的个人访问令牌,至少要有repo权限
const token = '你的GitHub个人访问令牌';

// 你的查询(和GraphiQL里一样就行)
const query = `
query GetRepoIssues($owner: String!, $name: String!, $label: String!) {
  repository(owner: $owner, name: $name) {
    issues(labels: [$label], states: OPEN) {
      nodes {
        title
        number
      }
    }
  }
}
`;

// 变量参数
const variables = {
  owner: '你的用户名/组织名',
  name: '仓库名',
  label: '你要筛选的标签'
};

// 带认证头请求
request(endpoint, query, variables, {
  headers: {
    Authorization: `Bearer ${token}`
  }
})
.then(data => console.log('拿到数据啦:', data))
.catch(err => console.error('出错了:', err));

3. 再核对下查询字符串有没有拼写错误

虽然你说GraphiQL里正常,但复制粘贴到代码里的时候,偶尔会不小心丢个字符或者大小写搞错(比如把repository写成Repository),再仔细检查一遍准没错。

4. 试试更新graphql-request版本

如果你的graphql-request版本太老,可能存在一些兼容性问题。跑个命令更到最新版试试:

npm install graphql-request@latest

额外小技巧:批量查多个仓库的issues

如果你要同时查多个仓库的带标签issues,可以用片段(fragment)来简化代码,避免重复写相同的字段:

const query = `
# 定义一个共享的issue字段片段
fragment IssueDetails on Issue {
  title
  number
  createdAt
  url
}

query GetMultiRepoIssues {
  repoA: repository(owner: "orgA", name: "repoA") {
    issues(labels: ["bug"], states: OPEN) {
      nodes {
        ...IssueDetails
      }
    }
  }
  repoB: repository(owner: "orgB", name: "repoB") {
    issues(labels: ["bug"], states: OPEN) {
      nodes {
        ...IssueDetails
      }
    }
  }
}
`;

内容的提问来源于stack exchange,提问作者Vincent Mazel

火山引擎 最新活动