node.js - 如何在 Google Translate Node.js 代码中设置 API KEY
问题描述
我正在尝试创建一个使用 google translate api 的 Node.js 代码。我从谷歌文档(https://cloud.google.com/translate/docs/translating-text)获得了以下代码
但是当我运行它时,它显示“错误:请求缺少有效的 API 密钥”。我有钥匙,但我不知道如何以及在哪里设置它。
async function translate() { // Imports the Google Cloud client library
const { Translate } = require('@google-cloud/translate');
// Creates a client
const translate = new Translate();
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
const text = 'Hello, world!';
const target = 'ru';
// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];
console.log('Translations:');
translations.forEach((translation, i) => {
console.log(`${text[i]} => (${target}) ${translation}`);
});
}
translate()
解决方案
此页面设置身份验证说明您需要从创建服务帐户密钥页面下载凭据文件。然后可以将其添加到您的路径 ( .bashrc
) 中,如下所示:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
或者,您可以将上面的行添加到.env
项目根目录上的文件中,并在运行应用程序时获取它:
. ./.env
npm start
或者
sh -ac '. ./.env; npm start'
推荐阅读
- c++ - imageStore() 不适用于整数类型
- pytorch - 将 BCE 损失与 ResNet 输出一起使用的适当方法是什么?
- typescript - VS Code 中类似 WebStorm 的 TypeScript 方法覆盖
- java - 如何使用 Java 计算给定字符串的子字符串中的总元音?
- flutter - 如何在 Firestore 中过滤特定文档的 Stream 客户端?
- google-apps-script - 我如何告诉应用脚本“进入下面的行”?
- javascript - 如何将所有文件 SRC 属性值重命名为小写?
- jquery - 如何添加到可与分页一起使用的表头动态数据行?
- java - 使用另一个类的方法的片段问题,Android Studio
- pandas - ImportError:DLL 加载失败:找不到指定的模块