I’m building a web application that aims to list files from Google Drive using JavaScript, but I’m encountering an issue. The error message indicates that the files property is undefined when I attempt to call the Drive API.
Here’s the code I’ve written so far:
var clientId = '123456789.apps.googleusercontent.com';
var apiKey = 'ABCDEFGHIJK';
var scopes = 'https://www.googleapis.com/auth/drive';
function initializeClient() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuthorization, 100);
}
function checkAuthorization() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthorizationResult);
}
function handleAuthorizationResult(authResult) {
var loginButton = document.getElementById('login-btn');
if (authResult && !authResult.error) {
loginButton.style.display = 'none';
executeDriveRequest();
} else {
loginButton.style.display = 'block';
loginButton.onclick = initiateAuth;
}
}
function initiateAuth(event) {
gapi.auth.authorize({client_id: clientId, scope: [scopes], immediate: false}, handleAuthorizationResult);
return false;
}
function executeDriveRequest() {
gapi.client.load('drive', 'v2', makeDriveRequest);
}
function makeDriveRequest() {
var request = gapi.client.drive.files.list({'maxResults': 10});
request.execute(function(response) {
for (var i = 0; i < response.items.length; i++) {
var fileTitle = response.items[i].title;
var modifiedDate = response.items[i].modifiedDate;
var lastModifiedBy = response.items[i].lastModifyingUserName;
var fileItem = document.createElement('div');
fileItem.textContent = 'File Name: ' + fileTitle + ' | Last Modified: ' + modifiedDate + ' | Modified By: ' + lastModifiedBy;
document.getElementById('file-list').appendChild(fileItem);
}
});
}
The error appears on the line: var request = gapi.client.drive.files.list({'maxResults': 10});
I’m getting this error: Uncaught TypeError: Cannot read property 'files' of undefined. What might be the reason for this issue? Is my method for loading the Drive API or the authentication process incorrect?