google translate 的简单实现

原创
2018/09/01 15:44
阅读数 200

google translate 的简单实现

const port = 3000
const fs = require('fs')
const path = require('path')
const spdy = require('spdy')
const express = require('express')
const bodyParser = require('body-parser');
const translate = require('google-translate-api')
const app = express()

app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.get('/fy',function(req,res){
	console.log(req.query);
	const fr = req.query.from;
	const to = req.query.to;
	const str = req.query.str
	if (!str || !to){
		res.send({err:'parma [to] and [str] must be null!!'});
		return;
	}

	translate(str,{to:to}).then(rtn=>{
		//console.log(rtn.text);
		//console.log(rtn.from.language.iso);
		res.set({ 'content-type': 'application/json; charset=utf-8' })
		res.send({v:rtn.text});
		}).catch(err=>{
			console.log(err);
		});
});

app.post('/fy',function(req,res){
	console.log(req.body);
	let fr = req.body.from
	let to = req.body.to
	let str = req.body.str
	if(!to || !str){
		res.send({rtn:'failed'});
		return;
	}
	
	translate(str,{to:to}).then(rtn=>{
		res.set({ 'content-type': 'application/json; charset=utf-8' })
		res.send({v:rtn.text});
		}).catch(err=>{
			console.log(err);
		});
});


app.get('/iso',(req,res) =>{
	//console.log(translate.languages);
	res.status(200)
	//.json({a:'asdf'});
	.json(translate.languages);
});

app.get('/help',(req,res) =>{
	res.status(200)
	.json({iso:'/iso', help:'/help',fy:'/fy'});
});

app.get('*',(req,res) =>{
	res.status(200)
	.json({message:'ok'});
});


function fy(from,to,str, cb){
	translate(str,{to:to}).then(rtn=>{
		console.log(rtn.text);
		console.log(rtn.from.language.iso);
		cb && cb(rest.text)
	}).catch(err=>{
		console.log(err);
	});
}

const options = {
	key: fs.readFileSync(__dirname + '/server.key'),
	cert: fs.readFileSync(__dirname + '/server.crt')
}

spdy
	.createServer(options, app)
	.listen(port, (error) =>{
	if(error){
		console.error(error)
		return porcess.exit(1)
	}else{
		console.log('Listening on port:' + port + '.')
	}
});

支持get 和post  方法,支持/help

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部