节点 js Google 驱动 api 错误

Node js Google drive api error

我正在尝试使用 Google Node.js client library 访问 Google 驱动器 API 以便我可以将一些文件上传到我的驱动器帐户,但我遇到了这个错误:

drive.files.create({
^

ReferenceError: drive is not defined
    at Object.<anonymous> (/Applications/MAMP/htdocs/google_drive/upload.js:16:1)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

我正在使用文档示例:

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

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) {
        // Handle error
        console.error(err);
    } else {
        console.log('File Id: ', file.id);
    }
});

任何人都可以帮助解决这个问题吗?

您需要先定义它。

var drive = google.drive("v3");

在 Google 的文档中查找合适的方法:

https://github.com/google/google-api-nodejs-client/#authorizing-and-authenticating

我认为您的 const google 声明应该改用解构赋值。如

const {google} = require(googleapis);

然后你声明 drive 像这样:

const drive = google.drive({version: 'v3',  auth});

其中 auth 是授权的 OAuth2 客户端。