使用NodeJS在Heroku上验证Google Sheet API [英] Authenticating Google Sheet API on Heroku using NodeJS

查看:245
本文介绍了使用NodeJS在Heroku上验证Google Sheet API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照以下示例访问Google表格API:

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



在示例中代码是以下方法来获取新的oauth标记。

 函数getNewToken(oauth2Client,回调){
var authUrl = oauth2Client.generateAuthUrl({
access_type:'offline',
scope:SCOPES
});
console.log('通过访问此URL授权此应用程序:',authUrl);
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout
});
rl.question('从该页面输入代码:',function(code){
rl.close();
oauth2Client.getToken(code,function(err,token) {
if(err){
console.log('尝试检索访问令牌时发生错误,错误);
返回;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});



$ b $ p
$ b

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

预先感谢。

https://console.developers.google.com 。这将生成一个JSON文件,其中需要两个值: private_key client_email



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

  GOOGLE_PRIVATE_KEY =<您的琴键这里-withouth的引号> 
GOOGLE_CLIENT_EMAIL =< your-email-here-withouth-quotes>

不要忘记将.env文件添加到您的.gitignore列表中,
$ b

我的 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(/ \\ / g,'\\\
'),
SCOPES
);

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


module.exports = {
授权,
}

请注意私钥变量后面的替换函数。



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

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

const SPREADSHEET_ID ='Your-spreadsheet-ID'; $(b

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('API返回错误:'+ err);
返回console.log(err);
}
var rows = response.values;
console.log (null,rows);
});
})
.catch((err)=> {
console.log('auth error',err);
});

如果出现以下错误:

API返回错误:错误:调用者没有权限



共享您尝试的电子表格使用google_client_email加载并重试。



如果本地一切正常,请通过访问您的heroku帐户并将<环境变量>添加到您的heroku应用程序并转至设置然后点击显示配置变量并部署应用程序。如果一切顺利,您应该可以访问文档。

I'm following this example to access the Google Sheets API:

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

Within the example code is the following method to fetch a new oauth token.

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);
    });
  });
}

This works fine on my local machine (manually visiting the page as prompted in the terminal, and entering the code in the command line). But this seems unpractical and doesn't work on Heroku. Is there any way to automate this? Maybe by fetching the URL (and token) in the nodeJS application and storing this somehow?

Thanks in advance.

解决方案

Ok, so I ended up using a Service Account Key which can be generated at https://console.developers.google.com. This will generate a JSON file of which you need two values: private_key and client_email.

To test this locally you can download the dotenv npm module which will allow you to store Environment variables in a .env file in your project root. Your .env file will look like this:

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

Don't forget to add the .env file to your .gitignore list when deploying your heroku app via git.

My auth.js file looks like this:

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,
}

Note the replace function behind the private key variable.

My app.js (main file) looks like this:

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);
    });

If you get the following error:

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

Share the spreadsheet you are trying to load with the google_client_email and try again.

If everything works locally, add the Environment Variables to your heroku app by visiting your heroku account and going to settings and click reveal config vars and deploy the application. If all goes well, you should have access to the document.

这篇关于使用NodeJS在Heroku上验证Google Sheet API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆