【发布时间】:2019-09-30 16:41:55
【问题描述】:
我想在我的 Node.js 应用程序中使用 Google 的云翻译 API,但是我收到了 The request is missing a valid API key. 错误。
我已经关注了谷歌提供的Quickstart guide。
我已经创建了 GCP 项目,将私钥下载为 JSON 文件,并在 Powershell (img) 中设置了环境变量。
之后我安装了这个库
yarn add @google-cloud/translate
我在 translate.js 文件中运行的代码来自快速入门指南,其中包含额外的 try-catch 块:
async function quickstart(
projectId = process.env.PROJECT_ID // Project Id from JSON file
) {
try {
// Imports the Google Cloud client library
const { Translate } = require('@google-cloud/translate');
// Instantiates a client
const translate = new Translate({ projectId });
// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';
// Translates some text into Russian
const [translation] = await translate.translate(text, target);
console.log('Text:', text);
console.log('Translation:', translation);
} catch (error) {
console.error(error);
}
}
quickstart();
然后当我运行 node translate.js 时,我会得到一个错误:
{ Error: The request is missing a valid API key.
...
code: 403,
errors:
[ { message: 'The request is missing a valid API key.',
domain: 'global',
reason: 'forbidden' } ],
response: undefined,
message: 'The request is missing a valid API key.' }
我使用的是 Windows 10,Node v10.13.0。
【问题讨论】: