Reputation: 194
I want use google translate api, so I made this node.js module.
module.exports = function(sourceText,sourceLang,targetLang,callback) {
var qst = qs.stringify({
client : 'gtx',
sl : sourceLang,
tl : targetLang,
dt : 't',
q : sourceText
});
var options = {
uri: 'http://translate.googleapis.com/translate_a/single?'+qst,
};
request.get(options).on('response',function(response){
response.on('data',function(data){
console.log(data.toString('utf-8'));
});
});..
I want mainly use translate japanese to korean, so I tested but I can't get result I wanted. I checked URI and execute on browser, it worked!
For example: sorceLang=ja, targetLang=ko, sourceText=ののの, I got URI
http://translate.googleapis.com/translate_a/single?client=gtx&sl=ja&tl=ko&dt=t&q=%E3%81%AE%E3%81%AE%E3%81%AE
Result on browser: [[["의의","ののの",,,0]],,"ja"]
But, node.js return result: [[["縺ョ縺ョ縺ョ","縺ョ縺ョ縺ョ",,,0]],,"ja"]
I think seems to be a problem in request, because result is not translated.
Please, give me some solution. Thank you.
Upvotes: 3
Views: 841
Reputation: 194
I got it!
Browser result is right. So, I set hearder 'User-Agent'. Here is my source
module.exports = function(sourceText,sourceLang,targetLang,callback){
var qst = qs.stringify({
client : 'gtx',
sl : sourceLang,
tl : targetLang,
dt : 't',
q : sourceText
});
var options = {
uri: 'http://translate.googleapis.com/translate_a/single?'+qst,
headers : {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'
}
};
request.get(options).on('response',function(response){
response.on('data',function(data){
console.log(data);
});
});}
Console result
[[["안녕하세요","こんにちわ",,,0]],,"ja"]
Thank you!
Upvotes: 2