[英]How set API KEY in Google Translate Node.js code
我正在嘗試創建一個使用谷歌翻譯 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()
此設置身份驗證頁面說明您需要從創建服務帳戶密鑰頁面下載憑據文件。 然后可以將其添加到您的路徑 ( .bashrc
) 中,如下所示:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
或者,您可以將上面的行添加到項目根目錄上的.env
文件中,並在運行應用程序時獲取它:
. ./.env
npm start
或者
sh -ac '. ./.env; npm start'
查看此Google 身份驗證頁面以添加密鑰
在 GCP Console 中,轉到創建服務帳戶密鑰頁面。
從服務帳戶列表中,選擇新建服務帳戶。
在服務帳戶名稱字段中,輸入名稱。
從角色列表中,選擇項目 > 所有者。 點擊
創建。 包含下載到計算機的密鑰的 JSON 文件。
和
export GOOGLE_APPLICATION_CREDENTIALS="[PATH to key downloaded]"
試試這個……沒有環境變量,請……將此文件添加到您的 .gitignore
import * as credentials from 'credentials.json';
...
const {Translate} = require('@google-cloud/translate').v2;
const translationApi = new Translate({
projectId:'your-project-id',
credentials:credentials
});
const translateClint = new tb.Translate({ projectId:'your-projectId-here', key: 'your-api-key-here', });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.