将 GitHub api接口请求次数从60次提升到5000次
在开发 aggna-cli 脚手架的过程中,我需要从GitHub远程仓库中获取所有的项目信息,接口为 https://api.github.com/users/zonghua2016/repos
(烦请各位大佬手下留情)
但是,请求了几次(60次)后就发现获取不到项目信息了,通过日志可以看到 GitHub API rate limit
的错误提示
这是由于在没有认证的情况下,github 默认访问次数只有每小时60次。可是我开发的是脚手架,可能很多人用的啊(虽然也不太可能…_),60次显然是不够的
可以通过 https://api.github.com/users/octocat 查询是否限制了, 如下
{
"message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
"documentation_url": "https://developer.github.com/v3/#rate-limiting"
}
一、破解次数限制
好了,既然找到了问题,就要有解决的方法啊
申请 access token 步骤:
进入github =>
点击头像 =>
点击 setting =>
Developer settings =>
Personal access tokens =>
点击右侧 Generate new token =>
在 Note 里添加备注,滚动页面到最底部,点击 Generate token 按钮
这时你就能看到新生成的 access token 啦!
那怎么验证请求次数是否真的增加了呢?
可以通过https://api.github.com/rate_limit?access_token=新生成的token 来验证
如图,limit已经增加到了5000次

二、如何使用
这里要注意 axios 添加 header 参数的格式
// 查询模板仓库
Project.prototype.getTemplateFromRepo = async function () {
const getTemplate = ora('🚀🚀🚀 正在获取模板,请稍等...')
getTemplate.start();
try {
const res = await axios({ url: 'https://api.github.com/users/zonghua2016/repos', method: 'GET', headers: { "Authorization": `token${gitToken}` } })
if (res.status === 200) {
getTemplate.color = 'green';
getTemplate.succeed('🏆 模板获取成功');
return res.data.filter(repo => {
if (repo.name.match(/aggna-(.*)-template/g)) {
return repo
}
})
}
} catch (error) {
getTemplate.color = 'red';
getTemplate.fail(`模板获取失败:${error.response.statusText} 😇😇😇`);
return;
}
}
网友评论