Encoding error with JSON request from StackOverflow API

I can’t figure it out for me. Below is the implementation with the request module, but I also tried with the node-XMLHttpRequest module to no avail.

var request = require('request'); var url = 'http://api.stackexchange.com/2.1/questions?pagesize=100&fromdate=1356998400&todate=1359676800&order=desc&min=0&sort=votes&tagged=javascript&site=stackoverflow'; request.get({ url: url }, function(error, response, body) { if (error || response.statusCode !== 200) { console.log('There was a problem with the request'); return; } console.log(body); // outputs gibberish characters like   console.log(body.toString()); // also outputs gibberish }); 

This seems to be a problem with the encoding, but I used the same code (with native XHR objects) in the browser and it works without problems. What am I doing wrong?

+6
source share
2 answers

Gzipped content. You can use request and zlib to unpack the streaming response from the API:

 var request = require('request') ,zlib = require('zlib'); var url = 'http://api.stackexchange.com/2.1/questions?pagesize=100&fromdate=1356998400&todate=1359676800&order=desc&min=0&sort=votes&tagged=javascript&site=stackoverflow'; request({ url: url, headers: {'accept-encoding': 'gzip'}}) .pipe(zlib.createGunzip()) .pipe(process.stdout); // not gibberish 

(Link: fooobar.com/questions/164098 / ... )

+10
source

While the answer is correct, there is an easier way to do this.

Since you are using a query, you can also add the gzip: true flag:

 var request = require('request'); var url = 'http://api.stackexchange.com/2.1/questions?pagesize=100&fromdate=1356998400&todate=1359676800&order=desc&min=0&sort=votes&tagged=javascript&site=stackoverflow'; request.get({ url: url, headers: {'accept-encoding': 'gzip'}, gzip: true }, function(error, response, body) { console.log(body); // not gibberish }); 
+5
source

All Articles