NodeJS返回垃圾JSON

时间:2015-04-20 20:06:59

标签: javascript json node.js

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

这是我定位的API - https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname=donal%20rafferty&site=stackoverflow

这是我的代码:

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 \ u0000uRn0 \ fB的ږ\ u00132 \ u0010R �m�u\\u0018\\u0004ڢ\\u001d!��Jr=�ȿ�vS\\u0004\\u0005������H����C 7րQN \ u0012 \ u0014 {克\\“] + ZV \ u001f(V%的|)QU.O \ u000e \u0012Ѹ\ u0005 \ U0003 \ u00130a \u0006BSӨC^ BWI \ u000bCb \ u0017e \ u0013q \\” DlO` @ ^ \ NQ \ u0017 |?իpFziR \ u000f,[PU {X \ b〜kLUV \ u0012 \ u00194l \ u000eڕ\ RW \ u001c * \ u001a9 \ u001eQ + Q> O;一个'\ BTI b /   \ u0007CK \ u0000jۯ\ u0003g | \ U0003 \ U0002 \ u0000的\ u0000的\

我假设我的编码/解码有问题,但我无法弄清楚该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

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

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");
    }
});
}