javascriptapigoogle-apigoogle-drive-apigoogle-picker

Google Drive api Error gapi.client.request


Hello guys I am using Google Picker API but when i comes to this code

var request1 =  gapi.client.request({
                        'path': '/drive/v3/files/' + fileID + '/permissions',
                        'method': 'POST',
                        'headers': {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + oauthToken
                        },
                        'body': {
                            'role': role,
                            'type': type
                        }
                    });
                    request1.execute(function (resp) {
                        console.log(resp);
                    });

I keep on getting error on gapi.client.request, you see in the image below. I don't what Im doing wrong here I also search alot in the google. And this code is also same with the code that I found in google and I need this to run in my website but I keep getting this error.

Any idea will do thank you. Uncaught TypeError: Cannot read properties of undefined (reading 'request')


Solution

  • Loading the library takes a bit of time to complete before it is fully loaded. So when you try to use gapi.client.request, gapi.client is still undefined.

    Make sure the library is loaded before proceeding.

    Sample:

    <body>
      Tester2
      <script>
        googleApiClientReady = function () {
          var request1 =  gapi.client.request({
            'path': '/drive/v3/files/' + fileID + '/permissions',
            'method': 'POST',
            'headers': {
              'Content-Type': 'application/json',           
              'Authorization': 'Bearer ' + oauthToken
            },
            'body': {
              'role': role,
              'type': type
            }
          });
          request1.execute(function (resp) {
            console.log(resp);
          });
        }
      </script>
      <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
    </body>
    

    Output:

    output

    Error now proceeds to undefined fileID instead of undefined gapi.client, inferring that the latter is now defined.

    Note: