我正在尝试使用node client访问google驱动器。这将在后台进程中的服务器上运行,而无需用户参与。在准备过程中,我已执行以下操作:
MyFolder
)共享驱动器中的特定文件夹。我能够成功验证为服务帐户并列出目录中的文件。但是,我无法下载任何文件。当我尝试时,我显然收到403错误。某种程度上,它隐藏在错误消息中,但这似乎是问题所在。这是我的代码:
const fs = require('fs');
const { google } = require('googleapis');
const auth = require('./service-creds.json');
(async () => {
let jwtClient = new google.auth.JWT(auth.client_email, null,
auth.private_key, ['https://www.googleapis.com/auth/drive']);
try {
const tokens = await jwtClient.authorize();
let drive = google.drive('v3');
const res1 = await drive.files.list({
auth: jwtClient, q: `name = 'MyFolder'`
});
const folder = res1.data.files[0];
const res2 = await drive.files.list({
auth: jwtClient,
q: `'${folder.id}' in parents`
});
// print out all files under MyFolder
res2.data.files.forEach(f => console.log(f.name, f.id));
const dest = fs.createWriteStream('./myfile.csv');
const file = res2.data.files[0];
const response = await drive.files.export({
fileId: file.id,
mimeType: file.mimeType,
auth: jwtClient
}, {
responseType: 'stream'
});
response.data.on('error', err => {
console.log(err);
}).on('end', () => {
console.log('done');
}).pipe(dest);
}
catch (err) {
console.log('The API returned an error: ', err);
}
})();
这是产生的错误的一部分:
The API returned an error:
... at Gaxios.<anonymous> (/api-test/node_modules/gaxios/build/src/gaxios.js:73:27)
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
Gunzip {
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 7,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
_transformState: [Object],
bytesRead: 0,
_opts: [Object],
_chunkSize: 16384,
_flushFlag: 2,
_finishFlushFlag: 2,
_scheduledFlushFlag: 0,
_handle: [Object],
_hadError: false,
_buffer: <Buffer 00 00 00 00 00 00 00 00 34 00 00 00 00 00 00 00 ... >,
_offset: 0,
_level: -1,
_strategy: 0 },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'https://www.googleapis.com/drive/v3/files/123abc123abc/export?mimeType=text%2Fplain',
status: 403,
statusText: 'Forbidden',
headers: Headers { [Symbol(map)]: [Object] },
counter: 0 } }
我无法找到任何错误,指出为什么抛出403。它似乎已压缩,但我无法成功解压缩它的任何部分。
答案 0 :(得分:1)
text/plain
文件。如果我的理解是正确的,那么该修改如何?
text/plain
的mimeType文件。
text/plain
的文件时,我可以确认发生相同的错误。为了反映以上几点,请进行以下修改。
const response = await drive.files.export({
fileId: file.id,
mimeType: file.mimeType,
auth: jwtClient
}, {
responseType: 'stream'
});
至:
const response = await drive.files.get({
fileId: file.id,
alt: "media",
auth: jwtClient
}, {
responseType: 'stream'
});