我正在尝试创建一个使用google translate api的Node.js代码。我从google doc(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()
This page on setting up authentication解释说您需要从创建服务帐户密钥页下载凭证文件。然后可以将其添加到您的路径(.bashrc
)中,如下所示:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
或者,您可以将上面的行添加到项目根目录上的.env
文件中,并在运行应用程序时将其源代码:
. ./.env
npm start
要么
sh -ac '. ./.env; npm start'
结帐这个Google Authentication Page添加密钥
- 在GCP控制台中,转到“创建服务帐户密钥”页面。
- 从“服务帐户”列表中,选择“新建服务帐户”。
- 在“服务帐户名称”字段中,输入名称。
- 从Role列表中,选择Project> Owner。点击
- 创建。包含密钥下载到计算机的JSON文件。
和
export GOOGLE_APPLICATION_CREDENTIALS="[PATH to key downloaded]"