问题
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