我已存储此服务帐户密钥(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)
3条答案
按热度按时间crcmnpdw1#
如果使用
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
中设置环境变量。jucafojl2#
能够使用npm运行,而无需每次设置凭据
关于如何使用env的更多原因,您可以访问如何从包内设置环境变量。json?更全面的答案。
7kqas0il3#
您也可以将其附加到进程。在导入@google-cloud npm库之前,使用env,如下所示:
为什么工作:
我怀疑google在导入环境变量时会检查它,而不是在你实际调用方法时检查它,这是必须先设置变量的。