【问题标题】:Google Cloud Throwing Error : Could not load the default credentials in Nodejs谷歌云抛出错误:无法在 Nodejs 中加载默认凭据
【发布时间】:2020-10-15 23:35:45
【问题描述】:

我已将此服务帐户密钥 (my-key.json) 文件存储在我的下载文件夹 (ubuntu) 中 然后我在控制台中运行这个命令

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

根据 google cloud。现在我正在运行此代码,但它会引发错误。

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)

【问题讨论】:

标签: javascript node.js google-cloud-platform google-api


【解决方案1】:

如果您使用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 包:

require('dotenv').config();

您也可以参考https://stackoverflow.com/a/27090755/7743705了解如何在pacakge.json中设置环境变量。

【讨论】:

  • 这正是问题所在!我尝试了一切,包括将其添加到环境中,但直接传递给节点命令有效! GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" 节点 .js
  • @RajaRao 很高兴它有帮助。如果我的回答解决了您的问题,请您接受我的回答。谢谢!
【解决方案2】:

为了能够使用 npm 运行而无需每次都设置凭据

"scripts": {
    "start": "set GOOGLE_APPLICATION_CREDENTIALS=[PATH]/credentials.json&& nodemon server.js"
},

有关如何使用 env 的更多原因,您可以访问 How to set environment variables from within package.json? 以获得更全面的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2018-11-23
    • 2020-05-01
    相关资源
    最近更新 更多