调用Google Drive API会返回Invalid_grant OAuth2

时间:2016-08-26 10:54:44

标签: javascript node.js ubuntu google-sheets node-modules

解决!

问题不在于我的代码。我在Linux服务器上手动设置时间,这意味着Google的服务器拒绝让我访问。我在服务器上使用了以下命令来设置时间:ntpdate 0.europe.pool.ntp.org

原始问题:

我目前正在尝试在NodeJS中开发一个小脚本,该脚本从Google电子表格中读取一些值,并将其写入JSON格式的文件中。

代码在我的Mac上没有任何问题,但在上传到Ubuntu 14.04.4后,“google-spreadsheet”模块中的某些功能无效并返回undefined。

我不是百分百肯定,节点模块是否有问题,或者我的代码是否有问题。

进行通话的代码:

var GoogleSpreadsheet = require('google-spreadsheet');
var fs = require('fs');

function scheduleBidding(sheetSecretKey) {
    this.sheetKey = sheetSecretKey;
}

scheduleBidding.prototype.getBiddingHeaders = function (filePrefix) {
var doc = new GoogleSpreadsheet(this.sheetKey);
var sheet;
var daysSinceYearStart = getDaysIntoYear();
var localSheetKey = this.sheetKey;
var biddingObject = new Object();
var filePath = filePrefix+"staticConfigFiles/googleApiKey";
console.log(filePath);
fs.readFile(filePath, 'utf8', function (err, data) {
    creds = JSON.parse(data);
    console.log(creds);
    doc.useServiceAccountAuth(creds, function (err) {
        if(err) throw err;
        doc.getInfo(function (err, info) {
            if(err) throw err;
            console.log(info);
            sheet = info.worksheets[0];
            var numberOfColumns = sheet.colCount;
            sheet.getCells({
                'min-row': 1,
                'max-row': 1,
                'min-col': 2,
                'max-col': numberOfColumns,
                'return-empty': true
            }, function(err, cells) {
                sheet.getRows({
                    offset: 1,
                    limit: 366
                }, function( err, rows ){
                    yesterdaysBid = rows[daysSinceYearStart-2];
                    todaysBidding = rows[daysSinceYearStart-1];
                    cells.forEach(function (listItem, indexArray) {
                        columnName = cells[indexArray].value;
                        var functionName = String(columnName.toLowerCase());
                        functionName = functionName.replace(/\s/g, '').replace(":", "");
                        biddingObject[columnName] = {
                            "yesterdaysBid": yesterdaysBid[functionName],
                            "todaysBid": todaysBidding[functionName]
                        };
                        newFileName = filePrefix+"scheduleData/"+localSheetKey+".json";
                        prettyJson = JSON.stringify(biddingObject);
                        fs.writeFile(newFileName, prettyJson);
                        console.log("ScheduleBidding JSON has been updated");
                    });
                });
            });
        });
    });
});

function getDaysIntoYear() {
    var todaysDate = new Date();
    var daysAgo;

    //
    returnDays = parseInt(todaysDate.getDate())+daysAgo;
    return returnDays;
}
};

我在Ubuntu服务器上执行脚本时收到以下异常:

    Error: invalid_grant
www-0     at Request._callback (/SomePath/node_modules/google-spreadsheet/node_modules/google-auth-library/node_modules/gtoken/lib/index.js:215:34)
www-0     at Request.self.callback (/SomePath/node_modules/google-spreadsheet/node_modules/google-auth-library/node_modules/gtoken/node_modules/request/request.js:187:22)
www-0     at Request.EventEmitter.emit (events.js:98:17)
www-0     at Request.<anonymous> (/SomePath/node_modules/google-spreadsheet/node_modules/google-auth-library/node_modules/gtoken/node_modules/request/request.js:1044:10)
www-0     at Request.EventEmitter.emit (events.js:95:17)
www-0     at IncomingMessage.<anonymous> (/SomePath/node_modules/google-spreadsheet/node_modules/google-auth-library/node_modules/gtoken/node_modules/request/request.js:965:12)
www-0     at IncomingMessage.EventEmitter.emit (events.js:117:20)
www-0     at _stream_readable.js:920:16
www-0     at process._tickDomainCallback (node.js:459:13)

提前感谢您的帮助。如果缺少任何信息,请告诉我。

2 个答案:

答案 0 :(得分:0)

在我看来,您的身份验证凭据丢失或不正确。您应该对useServiceAccountAuth回调中的可能错误做出反应。

var filePath = filePrefix+"/some/filePath.json"; // <- correct credentials?
doc.useServiceAccountAuth(creds, function (err) { 
  if(err) // handle error, you should see whats wrong
});

答案 1 :(得分:0)

感谢您的帮助!我终于解决了这个问题。这不是代码,而是我的服务器设置。我已经更新了这个问题,更具体地说明了这个问题。