Yur*_*Aps 8 google-translate api-key node.js google-cloud-platform
我正在尝试创建一个使用 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()
Run Code Online (Sandbox Code Playgroud)
有关设置身份验证的此页面说明您需要从创建服务帐户密钥页面下载凭据文件。然后可以将其添加到您的路径 ( .bashrc),如下所示:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
Run Code Online (Sandbox Code Playgroud)
或者,您可以将上面的行添加到.env项目根目录下的文件中,并在运行应用程序时获取它:
. ./.env
npm start
Run Code Online (Sandbox Code Playgroud)
或者
sh -ac '. ./.env; npm start'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2147 次 |
| 最近记录: |