I am building a web app that needs to list files from Google Drive using JavaScript. However, I am encountering an error related to the files endpoint and I’m not sure why.
Here is how I’ve implemented my code:
var clientId = '*********.apps.googleusercontent.com';
var apiKey = '##########';
var scopes = 'https://www.googleapis.com/auth/drive';
function loadClient() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuthorization, 1);
}
function checkAuthorization() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthorization);
}
function handleAuthorization(authResult) {
var loginBtn = document.getElementById('login-button');
if (authResult && !authResult.error) {
loginBtn.style.visibility = 'hidden';
makeApiCall();
} else {
loginBtn.style.visibility = '';
loginBtn.onclick = requestAuth;
}
}
function requestAuth(event) {
gapi.auth.authorize({client_id: clientId, scope: [scopes], immediate: false}, handleAuthorization);
return false;
}
function makeApiCall() {
gapi.client.load('drive', 'v2', executeApiCall);
}
function executeApiCall() {
var apiRequest = gapi.client.drive.files.list({'maxResults': 5});
apiRequest.execute(function(response) {
for (var i = 0; i < response.items.length; i++) {
var filename = response.items[i].title;
var lastModified = response.items[i].modifiedDate;
var modifiedBy = response.items[i].lastModifyingUserName;
var embedLink = response.items[i].embedLink;
var alternateLink = response.items[i].alternateLink;
var listItem = document.createElement('li');
listItem.appendChild(document.createTextNode('NAME: ' + filename + ' - LAST MODIFIED: ' + lastModified + ' - MODIFIED BY: ' + modifiedBy));
document.getElementById('file-content').appendChild(listItem);
}
});
}
The error I’m facing is:
Uncaught TypeError: Cannot read property 'files' of undefined
This occurs specifically at the line:
var apiRequest = gapi.client.drive.files.list({'maxResults': 5});
What might be the issue? The authentication seems to work fine but the API call does not.