NodeJS 谷歌翻译 API BAD_REQUEST

Nel*_*les 5 node.js google-translation-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);
});
Run Code Online (Sandbox Code Playgroud)

并出现以下错误消息

{ /var/www/translate/node_modules/google-translate-api/index.js:105:17 处的 process._tickCallback (internal/process/next_tick.js:160:7) 代码处出现错误: 'BAD_REQUEST' }

这是基本设置,如果有人解决了此问题,请发帖 - 感谢您的帮助。

小智 3

我建议您使用Google Cloud 的官方客户端库。但请注意,翻译 API没有免费配额。示例代码如下所示:

const {Translate} = require('@google-cloud/translate');

const projectId = 'YOUR_PROJECT_ID';

const translate = new Translate({   projectId: projectId, });

const text = 'Hello, world!'; 

const target = 'ru';

translate   
    .translate(text, target)   .then(results => {
      const translation = results[0];
      console.log(`Text: ${text}`);
      console.log(`Translation: ${translation}`);   
    })   
    .catch(err => {
      console.error('ERROR:', err);   
    });
Run Code Online (Sandbox Code Playgroud)