Http request to stackexchange api returns unreadable json

浪尽此生 提交于 2019-12-01 11:01:26

问题


I'm trying to fetch some json data from the stackexchange api. Receiving the OAuth code and access token works fine. But when calling the actual datafetching endpoints, the response does look wierd. Probably encoded or similar.

The request looks like this:

var client = requestjson.newClient('https://api.stackexchange.com');
    client.get("/2.2/me/comments?order=desc&sort=creation&site=stackoverflow&access_token="+myToken+"&key="+key, function(err, res, body) {
        console.log(body);
    })

And then the response body looks like this:

i�)�)QEJ�a��Ml�d4���20�c����M���]�v5/AZ�m��z    �C��`�~���*ͳ`Fh'����<M��k��J������J��>       &��ȗ����m��o>U�n�鴬�x=M��}1��m��'����ϻ��#
��zDn���n=ϳh[��QY��M���uv�*����&?;��S��х�V���'{mJ?  �8/�W�q���͓��+��qK��������X�9X~��g�������΁YrVY���B���X1#�`E

I've tried JSON.parse but it throws an error in the console.


回答1:


Found the answer myself here: node.js - easy http requests with gzip/deflate compression

Added the following:

var reqData = {
    url: "https://api.stackexchange.com/2.2/me/comments?order=desc&sort=creation&site=stackoverflow&access_token="+myToken+"&key="+key,
    method:"get",
    headers: {'Accept-Encoding': 'gzip'}
}
var gunzip = zlib.createGunzip();
var json = "";
gunzip.on('data', function(data){
    json += data.toString();
});
gunzip.on('end', function(){
    console.log(JSON.parse(json));
});
request(reqData)
    .pipe(gunzip)


来源:https://stackoverflow.com/questions/27386119/http-request-to-stackexchange-api-returns-unreadable-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!