Github API和Access-Control-Allow-Origin

jan*_*nce 6 ajax github github-api cors

这可能是一个简单的(系列)问题,但我无法绕过它.

我正在尝试从我网站上托管的网络应用程序访问github api.这是代码简而言之:

<!DOCTYPE html>
<html>
<head>
  <style>p { color:red; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function () {

$.ajax( {url :'https://api.github.com/repos/janesconference/kievIIPlugins/commits', dataType: "json", cache: false, success: function (data, textStatus, jqXHR)
        {
            var lastCommitSha = data[0].sha;
            $("p").text("Last commit SHA: " + lastCommitSha);
        }
    });
});
  </script>

</head>
<body>
  <p>Ajax request not (yet) executed.</p>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果我将浏览器指向我在Dropbox帐户上上传的这个简单页面,一切正常.相反,如果我将浏览器指向我网站上传的这个简单页面,我会得到臭名昭着的Access-Control-Allow-Origin例外:

XMLHttpRequest cannot load https://api.github.com/repos/janesconference/kievIIPlugins/commits?_=1360060011783. Origin http://bitterspring.net is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)

所以,问题:

  • 为什么它适用于Dropbox?
  • 据我所知,使用CORS它甚至可以在网站上运行.这是Access-Control-Allow-Origin: *.github.com我的Apache配置或类似的事情.但是,如引自en.wiki,

但是,这可能不适合担心安全问题的情况

  • 有没有办法在不更改Apache配置的情况下执行此操作?可能,我无法触及我的托管网站的Apache conf,并且始终存在安全问题.这样做的正确方法是什么?

Iva*_*zak 9

为了让CORS适用于您的站点(例如http://example.com),您必须通过在此处创建GitHub OAuth应用程序来启用它:https://github.com/settings/applications

由于您使用GitHub应用程序来使CORS正常工作(不使用它来启用OAuth本身),您只需在"创建应用程序表单"的所有三个字段中输入您站点的URL:

请注意,如果您打算使用OAuth功能,则需要以不同方式设置回调URL.

在此之后,您应该能够从您的站点http://example.com向GitHub API发送AJAX请求.

  • 即使它是`localhost`?因为我不能 (3认同)
  • _不使用它来启用 OAuth 本身_。这是什么意思?就我而言,我需要从我的站点(客户端 js)调用 Github API。为此,我希望我的用户使用 Github 进行身份验证,以便在此过程中我可以获得一些令牌供 Github API 调用使用。我怎么做?我需要注册 Github 应用程序吗? (2认同)