【问题标题】:TypeError: gapi.auth2.getAuthInstance(...) is null类型错误:gapi.auth2.getAuthInstance(...) 为空
【发布时间】:2017-10-26 14:37:36
【问题描述】:

我正在尝试编写一个使用 Google 距离矩阵 API 的工具, 但我一直遇到授权问题。我一直在工作 以下示例(无济于事):

https://developers.google.com/api-client-library/javascript/features/cors https://developers.google.com/identity/sign-in/web/devconsole-project https://developers.google.com/maps/documentation/distance-matrix/start

起初,我一直遇到 CORS 错误,我尝试使用它来修复 OAuth token,但现在我收到错误 TypeError: gapi.auth2.getAuthInstance(...) is null

<meta name="google-signin-client_id" content="MY_ID_HERE.apps.googleusercontent.com">
<script src="https://apis.google.com/js/api.js" type="text/javascript"</script>
<script type="text/javascript">
  gapi.load('auth2', function() {
    // Library loaded.
  });

window.onLoadCallback = function(){
    gapi.auth2.init({
        client_id: "MY_ID_HERE.apps.googleusercontent.com"
    });
}
</script>
<script>
function getDistance(){
var ds = document.getElementById("select-duty-station").value;
if(ds == "Choose One" || ds == ""){
    alert("Select a Duty Station");
    return false;
}

var dc = document.getElementById("text-destination").value;
if(dc == ""){
    alert("Destination is empty");
    return false;
}
var orig = "origins=" + ds.replace(" ", "+");
var dsts = "destinations=" + dc.replace(" ", "+");

var apiKey = "MY_KEY_HERE";
var url3 = "https://maps.googleapis.com/maps/api/distancematrix/json?" +
    orig + "&" + dsts + "&key=" + apiKey;
console.log(url3);

var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse().access_token;
var client3 = new XMLHttpRequest();
client3.open("GET", url3, false);
client3.onreadystatechange = function() {
    if(client3.readyState == 4){
        console.log(client3.responseText);
        var obj = JSON.parse(client3.responseText);
    };
};
client3.setRequestHeader("Authorization", "Bearer " + oauthToken);
client3.send();
}
</script>

我已经尝试了我能想到的一切;我在这里做错了什么?

【问题讨论】:

    标签: javascript google-distancematrix-api google-api-js-client


    【解决方案1】:

    您在调用 init 时缺少 scope 属性。

    window.onLoadCallback = function(){
        gapi.auth2.init({
            clientId: "MY_ID_HERE.apps.googleusercontent.com"
            scope: 'some scope here'
        });
    

    可以在此处找到 GAPI 范围参考:https://developers.google.com/identity/protocols/googlescopes

    另外,请确保为您的应用输入正确的clientId

    使用 Google API Javascript 库:

    https://developers.google.com/api-client-library/javascript/features/authentication https://developers.google.com/identity/protocols/OAuth2UserAgent

    【讨论】:

      猜你喜欢
      • 2015-07-01
      • 2018-05-01
      • 2019-02-23
      • 2018-09-08
      • 2014-01-10
      • 1970-01-01
      • 2021-03-24
      • 2015-03-06
      相关资源
      最近更新 更多