问题描述
我正在尝试创建一个使用 google translate api 的 Node.js 代码.我从谷歌文档(https://cloud.google.com/translate/docs/translating-text)
但是当我运行它时,它显示错误:请求缺少有效的 API 密钥."我有钥匙,但我不知道如何以及在哪里设置它.
async function translate() {//导入 Google Cloud 客户端库const { Translate } = require('@google-cloud/translate');//创建一个客户端const translate = new Translate();/*** TODO(开发人员):在运行示例之前取消注释以下行.*/const text = '你好,世界!';const 目标 = 'ru';//将文本翻译成目标语言.文本"可以是一个字符串//翻译一段文本,或用于翻译的字符串数组//多个文本.让 [translations] = await translate.translate(text, target);翻译 = Array.isArray(translations) ?翻译:[翻译];console.log('翻译:');translations.forEach((translation, i) => {console.log(`${text[i]} => (${target}) ${translation}`);});}翻译()
此页面设置身份验证 说明您需要从创建服务帐户密钥页面下载凭据文件.然后可以将其添加到您的路径 (.bashrc
) 中,如下所示:
导出 GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
或者,您可以将上面的行添加到项目根目录下的 .env
文件中,并在运行应用程序时获取它:
或
sh -ac '../.env;npm 开始'
I'm trying to create a Node.js code that uses google translate api.I got the code below from the google doc (https://cloud.google.com/translate/docs/translating-text)
But when I run it, it says "Error: The request is missing a valid API key."I have the key, but i don't know how and where to set it.
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 explains that you need to download a credentials file from the create service account key page. This can then be added to your path (.bashrc
) as follows:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
Alternately, you could add the line above to a .env
file on your project root and source it when you are running the application:
. ./.env
npm start
or
sh -ac '. ./.env; npm start'
这篇关于如何在 Google Translate Node.js 代码中设置 API KEY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!