[英]Authenticating Google Sheet API on Heroku using NodeJS
I'm following this example to access the Google Sheets API: 我按照此示例访问Google表格API:
https://developers.google.com/sheets/api/quickstart/nodejs https://developers.google.com/sheets/api/quickstart/nodejs
Within the example code is the following method to fetch a new oauth token. 在示例代码中,以下方法用于获取新的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);
});
});
}
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.
但这似乎不切实际,并不适用于Heroku。 Is there any way to automate this?
有没有办法自动化这个? Maybe by fetching the URL (and token) in the nodeJS application and storing this somehow?
也许通过在nodeJS应用程序中获取URL(和令牌)并以某种方式存储它?
Thanks in advance. 提前致谢。
Ok, so I ended up using a Service Account Key which can be generated at https://console.developers.google.com . 好的,所以我最终使用的服务帐户密钥可以在https://console.developers.google.com上生成。 This will generate a JSON file of which you need two values:
private_key
and client_email
. 这将生成一个JSON文件,您需要两个值:
private_key
和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. 要在本地测试,可以下载dotenv npm模块,它允许您将环境变量存储在项目根目录中的
.env
文件中。 Your .env
file will look like this: 您的
.env
文件如下所示:
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. 在通过git部署heroku应用程序时,不要忘记将.env文件添加到.gitignore列表中。
My auth.js
file looks like this: 我的
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,
}
Note the replace function behind the private key variable. 请注意私钥变量后面的替换功能。
My app.js (main file) looks like this: 我的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);
});
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. 使用google_client_email分享您尝试加载的电子表格,然后重试。
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. 如果一切都在本地运行,请通过访问您的heroku帐户并转到
settings
并单击reveal config vars
并部署应用程序,将环境变量添加到您的heroku应用程序。 If all goes well, you should have access to the document. 如果一切顺利,您应该可以访问该文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.