![](/img/trans.png)
[英]How Can I create a Google spreadsheet with two sheets in javascript using Google sheets API?
[英]How can I authenticate into Google Sheets API in Javascript without setting environment variables?
我現在正在按照這個在 Nodejs 中編寫一個腳本來寫入 Google Sheets API。 但是,事實證明我的系統不利於為此任務設置環境變量。 我有憑據 json,我想我可以將其內容作為變量放在我的腳本中,對嗎? 本教程說要設置的兩個環境變量是
export GCLOUD_PROJECT={project ID of your google project}
export GOOGLE_APPLICATION_CREDENTIALS=./service_account_credentials.json
我怎樣才能完成這項工作,以便我的代碼在不設置/更改任何環境變量的情況下進行身份驗證?
您很可能正在使用 googleapis npm 模塊。
您還可以通過 GoogleAuth 構造函數中的 keyFile 屬性指定服務帳戶憑據文件的路徑來使用 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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.