How set API KEY in Google Translate Node.js code

无人久伴 提交于 2020-03-22 11:03:50

问题


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()

回答1:


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'



回答2:


Checkout this Google Authentication Page to add the key

  1. In the GCP Console, go to the Create service account key page.

  2. From the Service account list, select New service account.

  3. In the Service account name field, enter a name.

  4. From the Role list, select Project > Owner. Click

  5. Create. A JSON file that contains your key downloads to your computer.

and

export GOOGLE_APPLICATION_CREDENTIALS="[PATH to key downloaded]"


来源:https://stackoverflow.com/questions/55732639/how-set-api-key-in-google-translate-node-js-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!