我需要以编程方式修改我的Google云端硬盘,以便能够创建文件夹并上传一堆文件,然后在需要时-删除该根文件夹并重做整个过程。
我创建了一个具有服务帐户的项目,然后下载了JSON,并将其存储在我的计算机上。接下来,我关注了this tutorial。
我最终得到了这段代码:
const auth = await google.auth.getClient({
credentials: require(pathToServiceAccountJSON),
scopes: "https://www.googleapis.com/auth/drive"
});
const drive = await google.drive({ version: "v3", auth });
drive.files
.create({
resource: {
name: filename,
mimeType: "application/vnd.google-apps.folder",
parents: [parentId]
}
})
.then(result => console.log("SUCCESS:", result))
.catch(console.error);
但是,执行它会引发以下错误:
{
...
errors: [{
domain: "global",
reason: "forbidden",
message: "Forbidden"
}]
}
第二,要访问驱动器,您必须在应用程序内请求适当的范围,并且必须通过访问将在授权过程中提供的URL来授权应用程序的请求权限(范围)。 Here is a guide to scopes。
const {JWT} = require('google-auth-library');
const keys = require('./jwt.keys.json');
async function main() {
const client = new JWT(
keys.client_email,
null,
keys.private_key,
['https://www.googleapis.com/auth/cloud-platform'],
'[email protected]'
);
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}
如果您没有G Suite帐户,则只需按照快速入门[3]步骤获得驱动器服务,然后使用它进行创建请求。[1] Do I need G Suite account to make requests impersonating an user with a service account?
[2] https://github.com/googleapis/google-auth-library-nodejs#json-web-tokens
[3] https://developers.google.com/drive/api/v3/quickstart/nodejs