2

I am using the following code to call the Stack Overflow API:

var request = require('request');
var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&site=stackoverflow';
request({
    headers: {
        'Accept': 'application/json; charset=utf-8',
        'User-Agent': 'RandomHeader'
    },
    uri: url,
    method: 'GET'
}, function(err, res, body) {
    console.log("response.statusCode" + res.statusCode);
    console.log("response.headers" + JSON.stringify(res.headers));
    console.log("res" + JSON.stringify(res));
    console.log("resParse" + JSON.parse(res));
});

}

This code returns the response as weird chars :

res{"statusCode":200,"body":"\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0004\u0000��{��H���\n�I�]M���̬U�5ݳ7=�3�ک�mݝN��L�t��\u0005\\\u001e�h��E��q�]����\\�\u0011�ɏxe��\"���\\���o�J?�\u001f���o�jq�X�����<���A?ݸv6Z���\u0012~F�N���v�?7�|��bq�ۢ��mՈ���Ŷ��Cj\u0016��b�I�\u001e��\u001b�����iY��\u001aw�\"Oҕ}H��ѝ\\Vզ�\r\u0002����m�c\u001b�����:�\bsJ\u0010f���\u0012��M\u001aW�¾w�߭t\u0001\u001an\u0016&-7+����)�_�Oz�}��\u0005�\\����*p�������\u0016�*���p�Y\u0006�m\u0007e-�?:��o\u0016i���rW��m�W��Y<�v�\u0010�۬��˛E3�;�n\u0016e�\u0017����e���*}J����\u0015\u001c��0,B���\".l��#����e}�-*\u0015��\u0018��gӉ�A'\u0013\u001c���\u0014��o\u001f3�undefined:1
[object Object]

Same code works for a different API call. Can someone suggest what's going wrong?

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
CodeMonkey
  • 2,265
  • 9
  • 48
  • 94
  • 1
    I saw a lot of characters like that when I was working with hex files. It might be hex or binary values that can't be represented by ascii. So you might want to look into parsing the body and converting that potential hex into readable characters. – bwalshy May 30 '16 at 07:24

3 Answers3

2

Stackoverflow uses compression to respond to your request. I've got the correct response using the following:

var request = require('request');
var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&site=stackoverflow';
request({
headers: {
    'Accept': 'application/json; charset=utf-8',
    'User-Agent': 'RandomHeader' 
         },
     uri: url,
     method: 'GET',
     gzip: true
         },
  function(err, res, body) {
     console.log("response.statusCode" + res.statusCode);
     console.log('server encoded the data as: ' + (res.headers['content-encoding'] || 'identity'))
     console.log('the decoded data is: ' + body)  
   });
George
  • 120
  • 1
  • 12
0

It has to do with the Accept-Encoding header.

Setting it explicitly to 'null' or '*' should solve the issue.

Alex MAN
  • 111
  • 1
  • 6
-1

My first answer is you should google JS Promise. My first guess is it must be promisified object. If it is an image, because of JS asynchronous nature, you must promisify it first. If it is not the promise, that is causing the issue, make sure that it is "UTF-8" supported languages.

DevBear15
  • 219
  • 4
  • 15