使用Google Node.js客户端库调用Drive API报错:drive未定义
解决
ReferenceError: drive is not defined 问题 兄弟,你遇到的这个错误太典型了——你直接用了上传文件的代码,但完全跳过了初始化Google Drive客户端的关键步骤!drive这个变量根本没被创建,自然会报未定义的错。
Google Drive API的示例代码其实默认你已经完成了OAuth2授权流程,但这部分是不能省略的,我给你补全完整的可运行代码,一步步给你解释:
完整修正代码
var fs = require('fs'); var readline = require('readline'); var google = require('googleapis'); var googleAuth = require('google-auth-library'); // 1. 配置授权信息(你需要从Google Cloud Console获取credentials.json) const SCOPES = ['https://www.googleapis.com/auth/drive.file']; const TOKEN_PATH = 'token.json'; // 加载客户端密钥文件 fs.readFile('credentials.json', (err, content) => { if (err) return console.log('加载credentials.json失败:', err); // 授权并初始化Drive客户端 authorize(JSON.parse(content), uploadFile); }); /** * 创建授权后的OAuth2客户端 */ function authorize(credentials, callback) { const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new googleAuth.OAuth2(client_id, client_secret, redirect_uris[0]); // 检查是否已有保存的token fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getAccessToken(oAuth2Client, callback); oAuth2Client.setCredentials(JSON.parse(token)); callback(oAuth2Client); }); } /** * 如果没有token,引导用户授权获取 */ function getAccessToken(oAuth2Client, callback) { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES, }); console.log('请访问此URL授权:', authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('请输入授权后的代码: ', (code) => { rl.close(); oAuth2Client.getToken(code, (err, token) => { if (err) return console.error('获取token失败:', err); oAuth2Client.setCredentials(token); // 保存token供下次使用 fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { if (err) return console.error('保存token失败:', err); console.log('token已保存到', TOKEN_PATH); }); callback(oAuth2Client); }); }); } /** * 上传文件到Google Drive */ function uploadFile(auth) { // 这里才是初始化drive对象! const drive = google.drive({version: 'v3', auth}); var fileMetadata = { 'name': 'photo.jpg' }; var media = { mimeType: 'image/jpeg', body: fs.createReadStream('files/photo.jpg') }; drive.files.create({ resource: fileMetadata, media: media, fields: 'id' }, function (err, file) { if (err) { console.error('上传出错:', err); } else { console.log('文件上传成功!File Id: ', file.id); } }); }
关键步骤说明
- 获取credentials.json:你需要先去Google Cloud Console创建一个项目,启用Drive API,然后创建OAuth2客户端ID,下载对应的
credentials.json文件,放到你的项目根目录。 - 授权流程:第一次运行代码时,会打印一个授权URL,你打开它登录你的Google账号,授权后会得到一个代码,输入到终端里,程序会自动生成
token.json,下次运行就不用再授权了。 - 初始化drive对象:在
uploadFile函数里,我们用授权后的auth对象创建了drive实例,这就是你之前代码里缺失的核心部分!
这样修改后,代码就能正常运行,不会再报drive is not defined的错误了。
内容的提问来源于stack exchange,提问作者Mhmd Backer Shehadi
相关产品推荐
相关产品推荐

