每次请求在 headers 中携带 Authorization 字段,值为 Basic + 空格 + base64("username:password")。react
须要在本地保存用户的帐户信息例如存入 localStorage。git
每次请求在 headers 中携带 Authorization 字段,值为 token + 空格 + accessToken。github
须要在本地保存用户的 access_token 例如存入 localStorage。json
须要在服务端注册一个 client app,获得 client_id 和 client_secret。api
利用 client_id 访问 /authorize 接口(可能须要声明 scope),页面重定向并获得 access code。跨域
利用 access code、client_id 和 client_secret 访问/login/oauth 接口,获得 access_token。缓存
鉴权方式这里选择 OAuth。app
打开 Github -> Settings -> Developer settings -> OAuth Apps -> New OAuth App 注册一个 app。cors
须要注意的是 Authorization callback URL 项: 当访问 /authorize 接口获取 access code 时,access code 会 以 url 参数的形式拼到这个 callback 后面(例如:'saber2pr.top/?code=xxxx'),并将页面重定向到此 url。dom
访问/authorize 接口获取 code 时,必定要带 scope=public_repo 参数!不能只带 client_id!
在页面的 js 脚本中,从 location.href 中解析出 code,而后利用 code 获取 access_token。
若是使用了 custom domain,获取 access_token 时可能会涉及到跨域问题,能够试试 cors-anywhere 方案。
准备一个 repo,在 repo 中开启一个 issue。每一个 issue 有一个序号,第一个 issue 序号就是 1。
issue 对应的评论 api 是 https://api.github.com/repos/${username}/${repo}/issues/${issue_id}/comments
访问这个 api 会获得该 issue 对应的评论。
若是须要能够带上 timestamp 时间戳,避免 api 被缓存没法更新。
GET(获取评论):
获取 saber2pr/rc-gitment 仓库中第一条 issue 的评论
fetch(
`https://api.github.com/repos/saber2pr/rc-gitment/issues/1/comments?timestamp=${Date.now()}`,
{
headers: {
Authorization: `token ${accessToken}`
}
}
).then(res => res.json())
复制代码
POST(发送评论):
在 saber2pr/rc-gitment 仓库中第一条 issue 下面添加一条评论,内容是 test from api.
注意 body 格式,{ body: string }
fetch(
`https://api.github.com/repos/saber2pr/rc-gitment/issues/1/comments?timestamp=${Date.now()}`,
{
method: "POST",
body: JSON.stringify({
body: "test from api."
}),
headers: {
Authorization: `token ${accessToken}`
}
}
)
复制代码
DELETE(删除评论):
删除地址是 commentToDeleteUrl 对应的评论。这个地址可在 GET 请求结果中获得,每条评论有一个对应的地址。
fetch(commentToDeleteUrl, {
method: "DELETE",
headers: {
Authorization: `token ${accessToken}`
}
})
复制代码
for react
具体效果看我博客