使用NodeJS在Heroku上validationGoogle Sheet API
我正在按照以下示例访问Google表格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); }); }); }
这在我的本地机器上正常工作(根据terminal提示手动访问页面,并在命令行中input代码)。 但是这似乎不切实际,并不能在Heroku上运行。 有什么办法可以自动化吗? 也许通过获取nodeJS应用程序中的URL(和令牌)并以某种方式存储它?
提前致谢。
好的,所以我最终使用了可以在https://console.developers.google.com上生成的服务帐户密钥。 这将生成一个您需要两个值的JSON文件: private_key
和client_email
。
要在本地进行testing,您可以下载dotenv npm模块,该模块将允许您将环境variables存储在项目根目录中的.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, }
请注意私钥variables后面的replace函数。
我的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帐户并添加环境variables到您的heroku应用程序并转到settings
,然后单击reveal config vars
并部署该应用程序。 如果一切顺利,您应该可以访问文档。