Node.js 调用百度翻译 API 实现无依赖翻译
学习笔记作者:admin日期:2025-05-31点击:20
摘要:使用 Node.js 原生模块实现百度翻译 API 调用,解决签名错误问题,无需任何外部依赖。
Node.js 调用百度翻译 API 实现无依赖翻译
问题描述
尝试使用百度翻译 API,但在签名验证时收到如下错误:
{"error_code":"54001","error_msg":"Invalid Sign"}
这表明签名(sign)生成不正确。
解决方案
通过检查签名生成逻辑和 API 请求参数,修复了签名问题,并实现了无依赖调用百度翻译 API 的功能。
关键步骤
- 确保使用正确的
client_id
和secret_key
。 - 按照百度翻译 API 文档,生成正确的签名字符串:
sign = md5(text + salt + secret_key)
。 - 发送请求时,确保
text
参数未被额外编码。
最终代码
const https = require('https');
const querystring = require('querystring');
const crypto = require('crypto');
// 替换为你的百度翻译 API 配置
const client_id = '你的client_id';
const secret_key = '你的secret_key';
function translate(text, fromLang = 'auto', toLang = 'zh') {
const salt = Math.floor(Math.random() * 1000000);
const input = text + salt + secret_key;
const sign = crypto.createHash('md5').update(input).digest('hex');
const params = querystring.stringify({
q: text,
from: fromLang,
to: toLang,
appid: client_id,
salt: salt,
sign: sign
});
const options = {
hostname: 'api.fanyi.baidu.com',
path: '/api/trans/vip/translate?' + params,
method: 'GET'
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
try {
const result = JSON.parse(data);
if (result.trans_result) {
resolve(result.trans_result.map(item => item.dst).join('\n'));
} else {
console.error('完整响应:', data);
reject('翻译失败: ' + data);
}
} catch (e) {
reject('解析失败: ' + e.message);
}
});
});
req.on('error', (e) => {
reject('请求出错: ' + e.message);
});
req.end();
});
}
// 测试调用
translate('Hello world', 'en', 'zh')
.then(console.log)
.catch(console.error);