1. 程式人生 > >Node.js http.request()返回響應出現亂碼的解決方案

Node.js http.request()返回響應出現亂碼的解決方案

之前用Node.js做個小程式,來實現校園網流量的查詢,以及對我校bt種子區搜尋條目刷單。當時用的是http.request(option,callback)方法,但返回的請求出現了亂碼的問題,這可把我給愁壞了。後來找到了方法,在這分享以方便遇到同樣問題的同學。

首先,show the code:

var http=require('http');
var options={
  hostname:'...',
  port:80,
  path:'/bt.php?'+searchstring,
  method:'GET'
};
var req=http.request(options,(res)=>{
    var
header=res.headers; console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); var html=''; res.on('data',(data)=>{ html+=data; }) res.on('end',()=>{ console.log(html); }) }); req.on('error'
,error=>{console.log("error:"+error.message)}); //req.write(searchstring);//因為我用的是get方法,所以並不用寫資料到請求頭 req.end();

這樣寫貌似沒有問題,但實際執行的時候卻發現返回的響應資料是亂碼,那怎麼辦,得找原因吧,按我為數不多的經驗來講一般是編碼的問題,但程式碼中我明確指定了所用編碼方式為“utf8”而且響應頭中字元編碼方式確實是“utf8”,不信你看返回的響應頭:

HEADERS: {"server":"Tengine","date":"Fri, 17 Feb 2017 14:03:58 GMT","content-type"
:"text/html; charset=utf-8","transferencoding":"chunked","connection":"keep-alive","set-cookie":[/*略去*/],"content-encoding":"gzip","vary":"Accept-Encoding"}

那是什麼原因那?我注意到內容編碼方式為“gzip”,gzip壓縮方式不就是壓縮html、css、js檔案什麼的,減少體積以加快響應嘛。難道是它的問題?是因為gzip壓縮使得返回的內容無法用utf8全部解出來導致出現亂碼嗎?當時我是半信半疑,先抱著試試的態度找下解決方案,費了好大功夫終於在stackoverflow中找到了解決方案(How to use request or http module to read gzip page into a string),看來還是stackoverflow大法好,最終解決方案如下:

var req=http.request(options,(res)=>{
    var header=res.headers;
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    var html='',output;
    if(res.headers['content-encoding']=='gzip'){
        var gzip=zlib.createGunzip();
        res.pipe(gzip);
        output=gzip;
    }else{
        output=res;
    }
    output.on('data',(data)=>{
        data=data.toString('utf-8');
        html+=data;
    });
    output.on('end',()=>{
        console.log(html);
    })
});
req.on('error',error=>{console.log("error:"+error.message)});
req.end(); 

就這樣我成功解決了一大難題,哈哈哈!