![](/img/trans.png)
[英]TwiML app and Firebase throwing Unhandled promise rejection: Error: Could not load the default credentials
[英]Google Cloud Throwing Error : Could not load the default credentials in Nodejs
我已將此服務帳戶密鑰(my-key.json)文件存儲在我的下載文件夾(ubuntu)中,然后我將此命令運行到我的控制台中
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"
根據谷歌雲。 現在我正在運行此代碼,但它會引發錯誤。
const language = require('@google-cloud/language');
const quickstart = async function () {
// Instantiates a client
const client = new language.LanguageServiceClient();
// The text to analyze
const text = 'Hello, world!';
const document = {
content: text,
type: 'PLAIN_TEXT',
};
// Detects the sentiment of the text
const [result] = await client.analyzeSentiment({document: document});
const sentiment = result.documentSentiment;
console.log(`Text: ${text}`);
console.log(`Sentiment score: ${sentiment.score}`);
console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
}
quickstart();
**ERORR** -
(node:13928) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:154:19)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async GoogleAuth.getClient (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:485:17)
at async GrpcClient._getCredentials (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:88:24)
at async GrpcClient.createStub (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:213:23)
如果您使用node <file-name>.js
來初始化您的代碼,您應該將命令更新為
GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" node <file-name>.js
這將使 GOOGLE_APPLICATION_CREDENTIALS 在您的節點環境中可用。
但是,作為長期解決方案,我建議創建一個.env
文件並將GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"
在該文件中。
然后按以下方式在js
文件的開頭使用dotenv
package:
require('dotenv').config();
您也可以參考https://stackoverflow.com/a/27090755/7743705
了解如何在pacakge.json
中設置環境變量。
為了能夠使用 npm 運行而無需每次都設置憑據
"scripts": {
"start": "set GOOGLE_APPLICATION_CREDENTIALS=[PATH]/credentials.json&& nodemon server.js"
},
有關如何使用 env 的更多原因,您可以訪問如何從 package.json 中設置環境變量? 以獲得更全面的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.