3

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.

Tirth Patel
  • 5,443
  • 3
  • 27
  • 39
yongsup
  • 184
  • 2
  • 8
  • Did you try `request.get(options, function(err, res, body) { console.log(body) })`? – mscdex Apr 02 '16 at 19:17
  • Yes, I tried. But result is same. こんにちわ body : [[["縺薙 s 縺ォ縺. SaaS는","縺薙s縺ォ縺。繧",,,0]],, @mscdex – yongsup Apr 03 '16 at 11:41

1 Answers1

2

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!

yongsup
  • 184
  • 2
  • 8