我现在正在遵循this在Nodejs中编写一个脚本,以写入到Google sheets API中。然而,事实证明,我的系统不利于为此任务设置环境变量。我有凭据json,我想我可以把它的内容作为一个变量放在我的脚本中,对吧?本教程提到要设置的两个环境变量是
export GCLOUD_PROJECT={project ID of your google project}
export GOOGLE_APPLICATION_CREDENTIALS=./service_account_credentials.json我如何才能做到这一点,这样我的代码可以在不设置/更改任何环境变量的情况下进行身份验证?
发布于 2020-09-19 00:58:52
您最有可能使用的是googleapis npm模块。
还可以使用keyFile属性,方法是通过GoogleAuth构造函数中的keyFile属性指定服务帐户凭据文件的路径:
const {google} = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFile: '/path/to/your-secret-key.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
}); 您还可以将auth设置为全局或服务级别选项,这样就不需要在每次请求时都指定它。例如,您可以将auth设置为全局选项:
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
// set auth as a global default
google.options({
auth: oauth2Client
});
Instead of setting the option globally, you can also set the authentication client at the service-level:
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
const drive = google.drive({
version: 'v2',
auth: oauth2Client
});https://stackoverflow.com/questions/63959579
复制相似问题