NodeJS返回垃圾JSON

我正在尝试使用NodeJS编写一段简单的代码来从堆栈交换API中获取JSON。

这是我所瞄准的API – https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname=donal%20rafferty&site=Tackoverflow

这是我的代码:

var https = require('https'); //Use NodeJS https module function getUserDataByName(userName, callback){ var stackOverflowUserURL = 'https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname='+encodeURIComponent(userName)+'&site=stackoverflow'; https.get(stackOverflowUserURL, function(response){ console.log("headers: ", response.headers); if (response.statusCode == 200) { var jsonString = ''; response.on('data', function (chunk) { jsonString += chunk; }); response.on('end', function () { console.log((jsonString)); callback(JSON.stringify(jsonString)); }); } else{ //error console.log("Error"); } }); } 

但是,当我运行这个数据总是回到像下面这样的文本垃圾状态:

“\u001f \ b \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0004 \u0000uR n 0\f B \u0013 2\ m u\\u0018\\u0004ڢ\\u001d! Jr= ȿ vS\\u0004\\u0005 H C u u u {{{ “] + ZV \ u001f(V%的|)QU.O \ u000e \u0012Ѹ\ u0005 \ U0003 \ u00130a \ u0006B SӨC^ BWI \ u000bCb \ u0017e \ u0013q \\“DlO` @ ^ \ NQ \ u0017 | ի?pFziR \ u000f,[PU {X \ b〜kLUV \ u0012 \ u00194l \ u000eڕ\ RW \ u001c * \u001a 9 \u001e Q+ Q > o ; a'\btI b/ \u0007 CK \u0000 jۯ \ u0003g | \ U0003 \ U0002 \ u0000的符\ u0000 \

我假设我的编码/解码有问题,但我不知道该怎么做才能解决这个问题?

       

网上收集的解决方案 "NodeJS返回垃圾JSON"

你需要解码响应,因为它被压缩

 var https = require('https'); //Use NodeJS https module var zlib = require("zlib"); function getUserDataByName(userName, callback){ var stackOverflowUserURL = 'https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname='+encodeURIComponent(userName)+'&site=stackoverflow'; https.get(stackOverflowUserURL, function(response){ console.log("headers: ", response.headers); console.log(response.statusCode) if (response.statusCode == 200) { var gunzip = zlib.createGunzip(); var jsonString = ''; response.pipe(gunzip); gunzip.on('data', function (chunk) { jsonString += chunk; }); gunzip.on('end', function () { console.log((jsonString)); callback(JSON.stringify(jsonString)); }); gunzip.on('error', function (e) { console.log(e); }); } else{ //error console.log("Error"); } }); }