首页 > 解决方案 > 如何使用 CORS 下提供的代码 github 获取用户访问令牌?

问题描述

我将 github 的 oauth2 应用到我的网站并获取临时代码。但我不知道如何将其推送到 github 并获取访问令牌以及如何使用令牌获取用户信息。

现在,我尝试了

https://github.com/login/oauth/access_token?client_id= "+ClientID+"&client_secret="+ClientSecret+"&code="+code

并获得一个包含访问令牌的非扩展文件。并且我想在不离开页面的情况下从该文件中拖动该令牌。我已经检查了指南,但我不知道应该如何在纯 HTML 和 JAVASCRIPT 代码中使用 PUT 和 GET。

var GET = {};
var queryString = window.location.search.replace(/^\?/, '');
queryString.split(/\&/).forEach(function(keyValuePair) {
    var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
    var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
    GET[paramName] = paramValue;
});
var code = GET["code"];
var auth = GET["auth"];
const ClientID = "ed2326bbcc88ed66ac15";
const ClientSecret = "ecc0ed28ea801bbe5ccdeb006f10374f0f0642dd";
$(function() {
    console.log(code);
    console.log(auth);
    if(auth === "github"){
        var target = "https://github.com/login/oauth/access_token?client_id="+ClientID+"&client_secret="+ClientSecret+"&code="+code;
        console.log(target);

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = process;
        xhr.open("GET", target, true);
        xhr.send();

        console.log(xhr);

        function process()
        {
            if (xhr.readyState == 4) {
                var resp = JSON.parse(xhr.responseText);

                // resp now has the text and you can process it.
                alert(resp);
            }
        }

                // window.onload = function() {
                //     /**
                //      * 上传函数
                //      * @param fileInput DOM对象
                //      * @param callback 回调函数
                //      */
                //     var getFileContent = function (fileInput, callback) {
                //         console.log(target.files);
                //         var reader = new FileReader();
                //         console.log(reader.readAsText(target, 'UTF-8'));
                //         console.log("fileInput.files", fileInput.files);
                //         if (
                //             fileInput.files && fileInput.files.length > 0 && fileInput.files[0].size > 0
                //             // target.files
                //         ) {
                //             //下面这一句相当于JQuery的:var file =$("#upload").prop('files')[0];
                //             var file = fileInput.files[0];
                //             if (window.FileReader) {
                //                 var reader = new FileReader();
                //                 reader.onloadend = function (evt) {
                //                     if (evt.target.readyState == FileReader.DONE) {
                //                         callback(evt.target.result);
                //                     }
                //                 };
                //                 // 包含中文内容用gbk编码
                //                 reader.readAsText(file, 'gbk');
                //             }
                //         }
                //     };
                //
                //     /**
                //      * upload内容变化时载入内容
                //      */
                //         document.getElementById('upload').onchange = function () {
                //             var content = document.getElementById('content');
                //
                //             getFileContent(this, function (str) {
                //                 content.value = str;
                //             });
                //         };
                // };

        $("#my-github-projects").loadRepositories("jashkenas", code);
        // jQuery.getJSON(target,function(data) {
        //     var repos = data.data;
        // });
    }
});

jQuery.githubUser = function(username, callback) {
    console.log('https://api.github.com/users/'+username+'/repos?callback=?',callback);
   jQuery.getJSON('https://api.github.com/users/'+username+'/repos?callback=?',callback)
};

jQuery.fn.loadRepositories = function(username) {
    this.html("<span>Querying GitHub for " + username +"'s repositories...</span>");

    var target = this;
    $.githubUser(username, function(data) {
        var repos = data.data; // JSON Parsing
        sortByName(repos);    

        var list = $('<dl/>');
        target.empty().append(list);
        $(repos).each(function() {
            if (this.name != (username.toLowerCase()+'.github.com')) {
                list.append('<dt><a href="'+ (this.homepage?this.homepage:this.html_url) +'">' + this.name + '</a> <em>'+(this.language?('('+this.language+')'):'')+'</em></dt>');
                list.append('<dd>' + this.description +'</dd>');
                list.append('<dd><em>Size: '+(this.size<1000?(this.size+' kB'):(Math.round((this.size/1000)*100)/100+' MB'))+' - Watchers: '+this.watchers+' - Forks: '+this.forks+' - Stars: '+this.stargazers_count+' </em></dd>');
                list.append('<dd><em>Updated At: '+ this.updated_at +'</em>');
                list.append('<dd><br/></dd>');
            }
        });      
      });

    function sortByName(repos) {
        repos.sort(function(a,b) {
        return a.name - b.name;
       });
    }
};

UPDATE: By using the code above and an extent on Chrome to avoid CORS, now I can get the information inside the file. But I cannot do it at the client side as it claims the "requested resource", which should be the github's access token, does not have the heading CORS needs and refuses me to access.

标签: javascripthtmlhttpgithubgithub-api

解决方案


I just found a way in another question to get around the CORS.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Hope this helps anyone who may be facing the same problem like this.


推荐阅读