为 Node.js 使用 google-translate-api 库时出现问题

Issues while working with google-translate-api library for Node.js

我是 javascript.I 的初学者,我正在尝试使用 google-translate-api

检测语言和翻译语言

我想免费使用 google 翻译 API 这就是我想使用它的原因。但是当我 运行 下面这样的任何代码时,

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' }

我尝试了更多 google 翻译 API 来自 GitHub 的库。 None 这项工作。 我也试过这个图书馆! another google-translate-api library 但是得到这个。

{ 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' } 

我该如何解决这个问题?

如果您查看图书馆 github 页面 - https://github.com/matheuss/google-translate-api, you could see that project is outdated, and there a lot of issues, with the same as yours - https://github.com/matheuss/google-translate-api/issues/70

我推荐你使用官方Google的翻译API。您可以通过 Google 翻译 API here.

找到如何使用 Node JS

使用方法:

首先,你需要安装库:

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}`);
}