I am trying to write a simple piece of code using NodeJS to return JSON from the stack exchange API.
This is the API I'm aiming for: https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname=donal%20rafferty&site=stackoverflow
And here is my code:
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"); } }); }
However, when I run this, the data always returns to the garbage state, for example, the following:
\ "\ 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 {r \\ "] + ZV \ u001f (V% ap |) QU.O \ u000e \ u0012ΡΈ \ u0005 \ u0003 \ u00130a \ u0006BSΣ¨C ^ tier 2 u001c * \ u001a9 \ u001eQ + Q> o, and '\ btIb / \ U0007CK \ u0000j Ϋ― \ u0003g | \ u0003 \ u0002 \ u0000 \ u0000 \
I assume that something is wrong with my encoding / decoding, but I cannot figure out what to do to fix this?
source share