Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I keep getting a auth2 is not defined? [duplicate]

I am trying to integrate the google signing button onto my web application. Its my first time doing it, and I keep getting the following message in my console log...

auth2 is not defined

Also when I refresh the page the google button says "Sign In" instead of "Signed In"

Below is my code. Thanks!

 <script>


    gapi.load('auth2', function () {
        auth2 = gapi.auth2.init();

        // Sign the user in, and then retrieve their ID.
        auth2.signIn().then(function () {
            console.log(auth2.currentUser.get().getId());
        });




    });


    if (auth2.isSignedIn.get()) {
  var profile = auth2.currentUser.get().getBasicProfile();
  console.log('ID: ' + profile.getId());
  console.log('Full Name: ' + profile.getName());
  console.log('Given Name: ' + profile.getGivenName());
  console.log('Family Name: ' + profile.getFamilyName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());
}


      function onSignIn(googleUser) {
        // Useful data for your client-side scripts:
        var profile = googleUser.getBasicProfile();
        console.log("ID: " + profile.getId()); // Don't send this directly to your server!
        console.log('Full Name: ' + profile.getName());
        console.log('Given Name: ' + profile.getGivenName());
        console.log('Family Name: ' + profile.getFamilyName());
        console.log("Image URL: " + profile.getImageUrl());
        console.log("Email: " + profile.getEmail());

        // The ID token you need to pass to your backend:
        var id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);
      }











    </script>
like image 613
json4 Avatar asked Aug 11 '16 19:08

json4


1 Answers

Don't let Google API mislead you. The error is probably because of this line (and the code being in ('strict mode'):

auth2 = gapi.auth2.init();

as the error states that "auth2" is not defined (and you are not allowed to create variables in the global space while in strict mode). Declare it like:

var auth2 = gapi.auth2.init();

Same thing happening here gapi auth2 init failing with "Uncaught ReferenceError: auth2 is not defined".

like image 53
Rocío García Luque Avatar answered Nov 07 '22 09:11

Rocío García Luque