Javascript 使用Node.js的google translate api库时出现的问题
我是javascript的初学者。我正在尝试使用javascript检测语言并翻译语言 我想免费使用谷歌翻译API,这就是为什么我想使用它。但是当我运行下面这样的代码时Javascript 使用Node.js的google translate api库时出现的问题,javascript,node.js,translation,google-translate,Javascript,Node.js,Translation,Google Translate,我是javascript的初学者。我正在尝试使用javascript检测语言并翻译语言 我想免费使用谷歌翻译API,这就是为什么我想使用它。但是当我运行下面这样的代码时 const translate = require('google-translate-api'); translate('Ik spreek Engels', {to: 'en'}).then(res => { console.log(res.text); //=> I speak English
const translate = require('google-translate-api');
translate('Ik spreek Engels', {to: 'en'}).then(res => {
console.log(res.text);
//=> I speak English
console.log(res.from.language.iso);
//=> nl
}).catch(err => {
console.error(err);
});
我得到这个错误
{ Error
at F:\Extensionproject\testTranslate\node_modules\google-translate-api\index.js:105:17
at process._tickCallback (internal/process/next_tick.js:68:7) code: 'BAD_REQUEST' }
我从GitHub尝试了更多google translate API库。这些都不管用。
我也试过这个图书馆!但是得到这个
{ HTTPError
at translate (F:\Extensionproject\testTranslate\node_modules\@k3rn31p4nic\google-translate-api\src\index.js:148:19)
at process._tickCallback (internal/process/next_tick.js:68:7)
name: 'HTTPError',
statusCode: 429,
statusMessage: 'Too Many Requests' }
如何解决此问题?如果您查看library github页面-,您会发现该项目已过时,并且存在许多问题,与您的一样- 我建议你使用谷歌官方的翻译API。您可以找到如何在GoogleTranslateAPI中使用NodeJS 如何使用它:
async function someFunction() {
// 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 = 'fr';
// Translates some text into French
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
首先,您需要安装库:
npm install @google-cloud/translate
然后,要使用它:
async function someFunction() {
// 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 = 'fr';
// Translates some text into French
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
谢谢,@BSeitkazin。我已经将您的代码用于projectd='translate-api-242605'。但是,如果我删除“等待我得到另一个错误”类型错误:translate.translate不是一个函数或者它的返回值不可iterable,我会得到错误“SyntaxError:await仅在异步函数中有效”“@MituVinci,更新了示例。您应该在一些
async
函数中发布示例代码。@MituVinci,如果答案有用,请将其标记为正确答案。如果你有另一个问题,就再提出一个问题。谢谢。你的代码很好用。但它需要谷歌翻译API密钥,这不是免费的。然而,我在一个新的项目目录中尝试了这个库,现在它工作得很好!不需要任何密钥或id:D@MituVinci,强烈建议使用官方API。然后,根据谷歌翻译API,它是免费的,每月1-500000个字符。我认为这对于自己的项目来说已经足够了。