我在Node.js中遇到.discover方法的问题。我有这样一段代码:
googleapis.discover('oauth2', 'v2').execute(function(err, client){
if(!err)
callback(client);
});
它抛出错误:TypeError:Object#没有方法'discover' 但是在所有教程中都提到了这样一种方法。有谁知道什么是错的?
答案 0 :(得分:5)
我得到了同样的错误。我认为他们为Node更新了googleapis客户端。
请尝试按照新语法使用旧版本:
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var drive = google.drive({ version: 'v2', auth: oauth2Client });
答案 1 :(得分:4)
我得到了同样的错误。但环顾了几个小时后。我遇到了这个问题并意识到他们可能已经更改了API并且没有更新官方文档。
我也是通过这个链接(https://developers.google.com/drive/web/quickstart/quickstart-nodejs)
尝试这段代码
var googleapis = require('googleapis'),
readline = require('readline');
var CLIENT_ID = 'YOUR CLIENT ID HERE',
CLIENT_SECRET = 'YOUR CLIENT SECRET HERE',
REDIRECT_URL = 'YOUR REDIRECT URL HERE',
SCOPE = 'https://www.googleapis.com/auth/drive.file';
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var auth = new googleapis.OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
googleapis.discover('drive', 'v2').execute(function(err, client) {
var url = auth.generateAuthUrl({ scope: SCOPE });
var getAccessToken = function(code) {
auth.getToken(code, function(err, tokens) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
auth.credentials = tokens;
upload();
});
};
var upload = function() {
client.drive.files
.insert({ title: 'My Document', mimeType: 'text/plain' })
.withMedia('text/plain', 'Hello World!')
.withAuthClient(auth).execute(console.log);
};
console.log('Visit the url: ', url);
rl.question('Enter the code here:', getAccessToken);
});
经过几个小时的努力。在浏览了互联网上的其他文档/教程之后,我将quickstart.js改为了。
var googleapis = require('googleapis');
var OAuth2 = googleapis.auth.OAuth2;
var readline = require('readline');
var CLIENT_ID = 'YOUR CLIENT ID HERE',
CLIENT_SECRET = 'YOUR CLIENT SECRET HERE',
REDIRECT_URL = 'YOUR REDIRECT URL HERE',
SCOPE = 'https://www.googleapis.com/auth/drive.file';
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var drive = googleapis.drive({ version: 'v2', auth: oauth2Client });
var execute = function(err, client) {
var url = oauth2Client.generateAuthUrl({ scope: SCOPE });
var getAccessToken = function(code) {
oauth2Client.getToken(code, function(err, tokens) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = tokens;
upload();
});
};
var upload = function() {
console.log(client)
client.drive.files
.insert({ title: 'My Document', mimeType: 'text/plain' })
.withMedia('text/plain', 'Hello World!')
.withAuthClient(oauth2Client).execute(console.log);
};
console.log('Visit the url: ', url);
rl.question('Enter the code here:', getAccessToken);
};
execute();
它开始工作但是虽然我得到它输出要去的URL,但是在从URL粘贴授权代码后我收到错误。上传函数中的Client对象是未定义的,所以我得到一个类型错误,说“无法读取未定义的属性'驱动'”。如果有人知道这个问题,请告诉我。我也正在学习NodeJS。