提问者:小点点

Google Cloud抛出错误:无法加载Nodejs中的默认凭据


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

导出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)


共1个答案

匿名用户

如果正在使用node.js初始化代码,则应将该命令更新为

google_application_credentials=“/home/user/downloads/my-key.json”节点.js

这将使GOOGLE_APPLICATION_CREDENTIALS在节点环境中可用。

但是,作为一个长期解决方案,我建议创建一个.env文件,并将GOOGLE_APPLICATION_Credentials=“/home/user/downloads/my-key.json”存储在该文件中。

然后按以下方式在js文件的开头使用dotenv包:

要求('dotenv').config();

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