首页 > 解决方案 > 如何在 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()

标签: node.jsgoogle-cloud-platformgoogle-translateapi-key

解决方案


此页面设置身份验证说明您需要从创建服务帐户密钥页面下载凭据文件。然后可以将其添加到您的路径 ( .bashrc) 中,如下所示:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

或者,您可以将上面的行添加到.env项目根目录上的文件中,并在运行应用程序时获取它:

. ./.env
npm start

或者

sh -ac '. ./.env; npm start'

推荐阅读