javascript Google 登录 gapi undefined

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25665865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:48:27  来源:igfitidea点击:

Google Sign In gapi undefined

javascripthtmlgoogle-api

提问by RyanY

I am trying to enable sign in with google on my site. The button works, syncs with my account, but I can not access the userId from google. This is what's in my head.

我正在尝试在我的网站上启用使用 google 登录。该按钮有效,与我的帐户同步,但我无法从 google 访问 userId。这就是我的想法。

 <script type="text/javascript">
      (function() {
        var po = document.createElement('script');
        po.type = 'text/javascript'; po.async = true;
        po.src = 'https://plus.google.com/js/client:plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
      })();
      </script>

And this is where I'm trying to obtain the user Id. In the console I get the error message Uncaught ReferenceError: gapi is not defined.I thought I was calling gapiin the source above. Any help or suggestions would be much appreciated.

这就是我试图获取用户 ID 的地方。在控制台中,我收到错误消息,Uncaught ReferenceError: gapi is not defined.我以为我是gapi在上面的源代码中调用的。任何帮助或建议将不胜感激。

$('document').ready(function(){
        var request = gapi.client.plus.people.get({
      'userId' : 'me'
    });

    request.execute(function(resp) {
      console.log('ID: ' + resp.id);
      console.log('Display Name: ' + resp.displayName);
      console.log('Image URL: ' + resp.image.url);
      console.log('Profile URL: ' + resp.url);
    });
});

回答by rajesh ujade

Your code is calling gapi.client.plus.people.getmethod before loading the google api library https://plus.google.com/js/client:plusone.js. Hence you are getting gapi is not defined error.

您的代码gapi.client.plus.people.get在加载 google api 库之前调用方法https://plus.google.com/js/client:plusone.js。因此你得到了gapi is not defined 错误。

Approach to work-

工作方法-

  1. Why its not working?
  1. 为什么它不工作?

We are calling https://plus.google.com/js/client:plusone.jsasynchronously(non blocking) to improve the performance. With Async javascript file loading, you are not able to call the gapi method on body load.

我们正在https://plus.google.com/js/client:plusone.js异步调用(非阻塞)以提高性能。使用异步 javascript 文件加载,您无法在主体加载上调用 gapi 方法。

    <script type="text/javascript">
          (function() {
            var po = document.createElement('script');
            po.type = 'text/javascript'; po.async = true;
            po.src = 'https://plus.google.com/js/client:plusone.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(po, s);
    </script>
  1. To make the api call you first have to know javascript file is successfully loaded.
  2. For this you have to call method using callback. https://apis.google.com/js/client:plusone.js?onload=makeAPICall

  3. Write an api request & execution it in the callback method to get data.

  1. 要进行 api 调用,您首先必须知道 javascript 文件已成功加载。
  2. 为此,您必须使用回调调用方法。 https://apis.google.com/js/client:plusone.js?onload=makeAPICall

  3. 编写一个 api 请求并在回调方法中执行它以获取数据。

Check below example for this-

请检查以下示例 -

    <html>
    <head></head>
    <body>
    <span id="signinButton">
      <span
        class="g-signin"
        data-callback="signinCallback" 
        data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
        data-cookiepolicy="single_host_origin"
        data-scope="https://www.googleapis.com/auth/plus.login">
      </span>
    </span>
    <script type="text/javascript">      
      (function() {
         var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
         po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
         var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      })();
      function signinCallback(authResult) {
            if (authResult['status']['signed_in']) {
                    document.getElementById('signinButton').setAttribute('style', 'display: none');
                        makeAPICall();
            } else {
                console.log('Sign-in state: ' + authResult['error']);
            }
      }
            function makeAPICall(){
            gapi.client.load('plus', 'v1', function() {
              var request = gapi.client.plus.people.get({
                'userId': 'me'
              });
              request.execute(function (resp){
                console.log(resp);
                if(resp.id){
                  console.log('ID: ' + resp.id);
                }
                if(resp.displayName){
                  console.log('Display Name: ' + resp.displayName);
                }
                if(resp.image && resp.image.url){
                  console.log('Image URL: ' + resp.image.url);
                }
                if(resp.url){
                  console.log('Profile URL: ' + resp.url);
                }
              });
           });
      }
    </script>
    </body>
    </html>

Conclusion:Calling javascript API before loading the asynchronously client library.

结论:在加载异步客户端库之前调用 javascript API。

To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.

To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.