javascript - 谷歌云抛出错误:无法在 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"
在该文件中。
然后以下列方式使用文件dotenv
开头的包:js
require('dotenv').config();
您也可以参考https://stackoverflow.com/a/27090755/7743705
了解如何在pacakge.json
.
推荐阅读
- docker - docker minio 在开始时失败并出现错误:“磁盘路径已满”
- java - 没有合格的 bean,使用 Spring Data JPA 设置 2 个数据源
- ios - Swift SceneKit:为什么过早检测到节点之间的接触?
- python - 当恰好在两个正方形之间时,圆会改变其方向
- python - 从 PyPI 包创建 conda 包有什么意义吗?
- svg - 是否可以在不使用 Illustrator 之类的编辑器的情况下更改 svg 中线条的粗细?
- quarkus - 支持在热点上运行的 quarkus 的 Java 版本
- c++ - 如何使用正在运行的线程正确退出/返回主线程?
- python-3.x - ML 中是否有库或模型可用于将文本转换为结构化内容(如表格)
- sql-server - 如何将一行与 Visual Basic 中的特定 SQL 列相关联?