使用ServiceAccount调用Google Drive API无法获取文件夹问题
问题:使用ServiceAccount调用Google Drive API无法列出「我的云端硬盘」文件夹
我编写了如下代码,本应获取「我的云端硬盘(My Drive)」中的文件夹,但即使目标文件夹确实存在,日志仍显示“No folders found.”。已使用ServiceAccount认证,且credentials.json文件配置正确,请问可能的原因是什么?
const { google } = require('googleapis'); const fs = require('fs'); // Create an OAuth2 client with the given credentials const auth = new google.auth.GoogleAuth({ keyFile: './credentials.json', scopes: ['https://www.googleapis.com/auth/drive'] }); // Create a new instance of the Drive API const drive = google.drive({ version: 'v3', auth }); async function listFolders() { try { const response = await drive.files.list({ q: "mimeType='application/vnd.google-apps.folder' and trashed=false", fields: 'files(id, name)', orderBy: 'name' }); const folders = response.data.files; if (folders.length) { console.log('Folders:'); folders.forEach(folder => { console.log(`${folder.name} (${folder.id})`); }); } else { console.log('No folders found.'); } } catch (error) { console.error('Error listing folders:', error.message); } } listFolders();
可能的原因及解决办法
ServiceAccount拥有独立存储空间:ServiceAccount并非你的个人Google账号,它有自己专属的Drive存储空间,和你网页版看到的「我的云端硬盘」完全独立。当前代码访问的是ServiceAccount自身的Drive,自然找不到你个人Drive里的内容。
未将个人Drive内容共享给ServiceAccount:若要让ServiceAccount访问你个人Drive中的文件夹,需手动将目标文件夹(或其上级文件夹)共享给ServiceAccount的邮箱地址(可在
credentials.json的client_email字段中找到),共享权限至少设置为「查看者」。请求参数未指定访问个人Drive:默认情况下,
files.list接口仅返回ServiceAccount自身空间内的文件。完成共享后,需修改请求参数,指定访问个人Drive:
const response = await drive.files.list({ q: "mimeType='application/vnd.google-apps.folder' and trashed=false", fields: 'files(id, name)', orderBy: 'name', corpora: 'drive', driveId: '你的个人Drive ID', // 可在网页版Drive的「设置-关于」中查看 includeItemsFromAllDrives: true, supportsAllDrives: true });
内容的提问来源于stack exchange,提问作者TheRealLuckyGuyDev
相关产品推荐
相关产品推荐

