获取的数据是乱码,是怎么回事?
谁能帮我看看我的代码,帮我看看,我是个初学者,弄了好久,还是没弄出来,哪里出错了啊?获取到的数据不论是写到文件,还是读出来都是乱码,就这个样
var http = require('http'); var querystring = require('querystring'); var Promise = require('Promise'); // 若版本过低,可使用bluebird替换 var cheerio = require('cheerio'); // 类似于jQuery,安装方法:npm install cheerio var fs = require('fs'); var path = require('path'); var option={ hostname: "user.pospal.cn", port: 80, path:"/Product/Manage", method: "POST", headers:{ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch", "Accept-Language": "zh-CN,zh;q=0.8", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Cookie": "__ngDebug=true; Vid=V2FQZl1mXj5QNQE6WWU=; .POSPALAUTH30220=0102A061942D6F" + "84D308FEA0E15C7F6F8FD3080006350030003100350032003A0000012F00FFA5D1EE8E7CAB31C99" + "86D05F03CCD1198462091BE; Hm_lvt_7d46a3151782b7a795ffeba367b5387d=1462767802,146" + "2771728; Hm_lpvt_7d46a3151782b7a795ffeba367b5387d=1464480933; Hm_lvt_18c160bec8" + "a91b8858c74ff702e6c788=1463498456,1463575485,1464061183,1464394742; Hm_lpvt_18c" + "160bec8a91b8858c74ff702e6c788=1464513421; ASP.NET_SessionId=10ooianyuuk3mcjwbhqs3rls", "Host":"user.pospal.cn", "Referer": "http://user.pospal.cn/Product/CaseProductItem", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", } }; var req = http.request(option, function (res) { res.setEncoding('utf8'); var data = ''; console.log("Status:" + res.statusCode); console.log("headers:" + JSON.stringify(res.headers)); res.on('data', function (chunk) { console.log("is Buffer: " + Buffer.isBuffer(chunk)); console.log(typeof chunk); data += chunk; console.log(chunk.toString()); }); res.on('end', function () { console.log("shuju" + typeof data); console.log("数据获取完毕!"); fs.writeFile(path.join(__dirname, 'account.js'), data, (err) => { //fs.writeFile('account.js', data, (err) => { if (err) throw err; console.log('It\'s saved!'); }); filterHtml(data); }); }); req.on('error', function (e) { console.log("Error: " + e.message); }); req.end();