Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

ajax - Github API and Access-Control-Allow-Origin

this probably is a simple (series of) question(s) but I can't wrap my head around it.

I'm trying to access the github api from a web app hosted on my site. This is the code in a nutshell:

<!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>

If I point my browser to this simple page uploaded on my dropbox account everything is ok. If, instead, I point my browser to this simple page uploaded on my site, I get the infamous Access-Control-Allow-Origin exception:

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

So, the questions:

  • Why does it work on Dropbox?
  • I understand that with CORS it would work even on the website. This is a matter of putting Access-Control-Allow-Origin: *.github.com on my Apache configuration or something like that. But, as quoted from en.wiki,

However, this might not be appropriate for situations in which security is a concern

  • Is there a way to do this without changing the Apache configuration? Probably, I can't touch the Apache conf of my hosting site, and there's always the security concern. What is the right way to do this?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to get CORS working for your site (e.g. http://example.com), you have to enable it by creating a GitHub OAuth application here: https://github.com/settings/applications

Since you are using a GitHub applications to get CORS to work (not using it for enabling OAuth itself), you can just enter your site's URL in all three fields in the "Create Application form":

Note that if you intend to use OAuth functionality, you need to setup Callback URL differently.

After this, you should be able to send AJAX requests to GitHub APIs from your site http://example.com.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...