NodeJS returns JSON garbage

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?

+6
source share
1 answer

You need to decode the answer as it is gzipped

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

Source: https://habr.com/ru/post/985548/


All Articles