我正在尝试将我的 Electron 应用程序的一些用户数据存储到用户的 Google Drive 中。我正在使用“google-auth-library”和“googleapis”npm 包并尝试使用 OAuth2 协议(protocol),但我收到此错误:“API 返回错误:错误:未验证使用的每日限制已超出。继续使用需要注册。
我按照 https://developers.google.com/drive/api/v3/about-sdk 中的步骤进行操作和 https://developers.google.com/identity/protocols/OAuth2 ,所以我这样做了:
import { google } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';
async function googleSignIn() {
const oAuth2Client = new OAuth2Client({
clientId:
'xxxxxxyyyyzzzz.apps.googleusercontent.com',
redirectUri: 'com.xxx.yyyyyyy:/oauth2Callback'
});
const code = await signInWithPopup(oAuth2Client);
await oAuth2Client.getToken(code, (err, token) => {
if (err) {
return console.error('Error retrieving access token', err);
}
oAuth2Client.setCredentials(token);
listSomeFiles(oAuth2Client);
});
}
function signInWithPopup(oAuth2Client: OAuth2Client) {
return new Promise((resolve, reject) => {
const authWindow = new BrowserWindow({
width: 500,
height: 600,
show: true
});
const SCOPES = [
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.appfolder',
'https://www.googleapis.com/auth/drive.metadata.readonly'
];
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
function handleNavigation(url) {
const { query } = parse(url, true);
if (query) {
if (query.error) {
reject(new Error(`There was an error: ${query.error}`));
} else if (query.code) {
// Login is complete
authWindow.removeAllListeners('closed');
setImmediate(() => authWindow.close());
resolve(query.code);
}
}
}
authWindow.on('closed', () => {
throw new Error('Auth window was closed by user');
});
authWindow.webContents.on('will-navigate', (event, url) => {
handleNavigation(url);
});
authWindow.webContents.on(
'did-get-redirect-request',
(event, oldUrl, newUrl) => {
handleNavigation(newUrl);
}
);
authWindow.loadURL(authUrl);
});
}
async function listSomeFiles(oAuth2Client: OAuth2Client) {
const drive = google.drive({ version: 'v3', oAuth2Client });
// the following lines throws the error
// code snippet from https://developers.google.com/drive/api/v3/quickstart/nodejs
drive.files.list(
{
pageSize: 10,
fields: 'nextPageToken, files(id, name)'
},
(err, res) => {
if (err) return console.log(`The API returned an error: ${err}`);
const { files } = res.data;
if (files.length) {
console.log('Files:');
files.map(file => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
}
);
}
最佳答案
找到了原因,我的 api 请求中缺少一个参数“oauth_token”。我希望这可以开箱即用,因为我已将 oAuth2Client 对象(具有 token 信息)传递给 google.drive() 函数。
drive.files.list(
{
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
oauth_token: oAuth2Client.credentials.access_token
},
(err, res) => {
}
);
关于javascript - 为什么我在尝试从我的 Electron 应用程序调用 Google Drive Api 时收到 'Daily Limit for Unauthenticated Use Exceeded' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57755371/