Encoding issue with requesting JSON from StackOverflow API

梦想的初衷 提交于 2019-12-01 17:18:22
Pero P.

The content is gzipped. You can use request and zlib to decompress a streamed 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

(Reference: https://stackoverflow.com/a/14739453/112196)

While pero's answer is correct, there's a simpler way to do this.

Since you're using request, you can also just 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
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!