node.js request encoding (google translate)

笑着哭i 提交于 2019-12-22 09:42:00

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/36377532/node-js-request-encoding-google-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!