Nodejs 浏览器端能不能发 Github 的 Issue comment API?
Nodejs 浏览器端能不能发 Github 的 Issue comment API?
发现文档里有这个 API, 但是听说浏览器端是不能发送跨域 POST 的… 不过, 看文档上写的, 好像这个 API 不需要认证信息的? http://developer.github.com/v3/issues/comments/#create-a-comment
{
"body": "a new comment"
}
而且可以改写请求的 HTTP 头来允许跨域分享了…
http://developer.github.com/v3/#cross-origin-resource-sharing
$ curl -i https://api.github.com -H "Origin: http://some-site.com"
HTTP/1.1 302 Found
但按这个思路, 如果浏览器不经过验证就能评论的话, 岂不是太不安全了…
还是说 Github 的 API 文档老是省略 key 的? 有没有对付过 Github API 的大哥…
现在刚在搞这个,测试了一下,怎么发数据都是返回 { “message”: “Not Found” } 按操作一定要有OAuth key
在浏览器端直接使用 GitHub 的 Issue Comment API 发送评论存在一定的限制。由于同源策略(Same-Origin Policy)的存在,浏览器不允许未经身份验证的跨域 POST 请求。因此,你需要通过身份验证来绕过这些限制。
为了实现这一目标,你可以使用 GitHub 的 OAuth 应用程序来生成一个访问令牌,并将其包含在你的请求头中。以下是一个简单的示例,展示如何使用 fetch
在浏览器端发送 GitHub Issue Comment API 请求:
示例代码
首先,确保你有一个有效的 GitHub 访问令牌。然后,你可以使用下面的代码片段来发送请求:
async function postComment(owner, repo, issue_number, token, commentBody) {
const url = `https://api.github.com/repos/${owner}/${repo}/issues/${issue_number}/comments`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
body: commentBody
})
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
return await response.json();
}
// 使用示例
const owner = 'your-username';
const repo = 'your-repo';
const issue_number = 1;
const token = 'your-github-access-token';
const commentBody = 'This is a new comment';
postComment(owner, repo, issue_number, token, commentBody)
.then(data => console.log('Comment posted:', data))
.catch(error => console.error('Error posting comment:', error));
解释
- API URL: 构建 API URL 以指向特定仓库的特定问题的评论。
- Headers: 设置请求头,包括
Authorization
和Content-Type
。Authorization
头使用 Bearer 令牌进行身份验证。 - Body: 使用 JSON 格式发送评论内容。
- Fetch: 使用
fetch
发送 POST 请求,并处理响应。
安全性考虑
- 令牌管理: 保管好你的访问令牌,不要硬编码或暴露在客户端代码中。
- CORS 配置: GitHub 已经配置为允许来自不同源的请求,但你仍然需要通过身份验证。
以上就是如何在浏览器端使用 Node.js 发送 GitHub Issue Comment API 请求的方法。