【问题标题】:Authenticating Google Sheet API on Heroku using NodeJS使用 NodeJS 在 Heroku 上验证 Google Sheet API
【发布时间】:2017-09-11 20:49:54
【问题描述】:

我正在按照此示例访问 Google Sheets API:

https://developers.google.com/sheets/api/quickstart/nodejs

示例代码中包含以下获取新 oauth 令牌的方法。

function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

这在我的本地机器上运行良好(根据终端提示手动访问页面,并在命令行中输入代码)。但这似乎不切实际,并且不适用于 Heroku。有什么办法可以自动化吗?也许通过在 nodeJS 应用程序中获取 URL(和令牌)并以某种方式存储它?

提前致谢。

【问题讨论】:

标签: node.js heroku google-api google-oauth google-docs-api


【解决方案1】:

好的,所以我最终使用了可以在https://console.developers.google.com 生成的服务帐户密钥。这将生成一个 JSON 文件,您需要其中两个值:private_keyclient_email

要在本地进行测试,您可以下载dotenv npm 模块,它允许您将环境变量存储在项目根目录下的.env 文件中。您的 .env 文件将如下所示:

GOOGLE_PRIVATE_KEY=<your-key-here-withouth-quotes>
GOOGLE_CLIENT_EMAIL=<your-email-here-withouth-quotes>

在通过 git 部署你的 heroku 应用时,不要忘记将 .env 文件添加到你的 .gitignore 列表中。

我的auth.js 文件如下所示:

const GoogleAuth = require('google-auth-library');

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];

function authorize() {
    return new Promise(resolve => {
        const authFactory = new GoogleAuth();
        const jwtClient = new authFactory.JWT(
            process.env.GOOGLE_CLIENT_EMAIL,
            null,
            process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'), 
            SCOPES
        );

        jwtClient.authorize(() => resolve(jwtClient));
    });
}

module.exports = {
    authorize,
}

注意私钥变量后面的替换功能。

我的 app.js(主文件)如下所示:

require('dotenv').config();
const google = require('googleapis');
const sheetsApi = google.sheets('v4');
const googleAuth = require('./auth');

const SPREADSHEET_ID = 'Your-spreadsheet-ID';

googleAuth.authorize()
    .then((auth) => {
        sheetsApi.spreadsheets.values.get({
            auth: auth,
            spreadsheetId: SPREADSHEET_ID,
            range: "'Tab Name'!A1:H300",
        }, function (err, response) {
            if (err) {
                console.log('The API returned an error: ' + err);
                return console.log(err);
            }
            var rows = response.values;
            console.log(null, rows);
        });
    })
    .catch((err) => {
        console.log('auth error', err);
    });

如果出现以下错误:

The API returned an error: Error: The caller does not have permission

与 google_client_email 共享您尝试加载的电子表格,然后重试。

如果一切正常,请访问您的 heroku 帐户并转到 settings 并单击 reveal config vars 并部署应用程序,将环境变量添加到您的 heroku 应用程序。如果一切顺利,您应该可以访问该文档。

【讨论】:

  • 太棒了!现在我只需要检查这是否适用于 youtube 分析。我会及时通知你。
  • @peerbolte 很好地抓住了私钥上的replace。 API 文档 [github.com/theoephraim/node-google-spreadsheet#api]HEROKU 用户的特别说明 下有一个特别说明 - 但没有想到在密钥上做一个适当的 replace。省去了编辑文件的麻烦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-22
相关资源
最近更新 更多