首页 > 解决方案 > NodeJS google-translate-api BAD_REQUEST

问题描述

所以给出的例子如下

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

带有以下错误消息

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

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

标签: node.jsgoogle-translation-api

解决方案


我建议您使用Google Cloud 的官方客户端库。但请注意, Translate 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);   
    });

推荐阅读