最近有了翻译的需求,
想用node进行一波封装,
发现百度翻译api个人认证之后每个月有100万字符的免费额度,
足够我使用了,废话不多说 直接开搞
文档地址:http://api.fanyi.baidu.com/product/113
然后是我自己随便封装的(node环境)
先下载俩包axios(请求需要)和md5(翻译参数需求)
npm i md5 axios -S
然后就是具体的代码,我封装了一个promise来批量处理的
const md5 = require("md5");
const axios = require("axios");
// 请求参数:
// q=apple
// from=en
// to=zh
// appid=2015063000000001(请替换为您的appid)
// salt=1435660288(随机码)
// 平台分配的密钥: 12345678
// 生成签名sign:
// Step1. 拼接字符串1:
// 拼接appid=2015063000000001+q=apple+salt=1435660288+密钥=12345678得到字符串1:“2015063000000001apple143566028812345678”
// Step2. 计算签名:(对字符串1做MD5加密)
// sign=MD5(2015063000000001apple143566028812345678),得到sign=f89f9594663708c1605f3d736d01d2d4
const setUrl = (q, from, to) => {
let appid = "你的appid";
let appKey = "你的app密钥";
let salt = Date.now();
let sign = md5(appid + q + salt + appKey);
let url = `http://api.fanyi.baidu.com/api/trans/vip/translate?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`;
return url;
};
const translater = () => {
return new Promise((resolve) => {
let url = setUrl("test", "auto", "zh");
axios
.get(url)
.then((res) => {
console.log(res.data);
resolve(res.data);
})
.catch((err) => {
//这里异常也使用resolve抛出不然会进程阻塞 看具体需求进行改变
resolve(res.data);
});
});
};
translater();
sign=MD5(2015063000000001apple143566028812345678),得到sign=f89f9594663708c1605f3d736d01d2d4
let setUrl = (q, from, to) => {
let appid = "你的appid";
let appKey = "你的api密匙";
let salt = Date.now();
let sign = md5(appid + q + salt + appKey);
let url = `http://api.fanyi.baidu.com/api/trans/vip/translate?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`;
return url;
};
const translater = () => {
let url = setUrl("test", "auto", "zh");
axios.get(url).then((res) => {
console.log(res.data);
});
};
translater();
完事了 拜拜!