Search code examples
jsonnode.jsstack-overflow

getting garbage JSON from stack-overlfow api in node.js


I am searching for a question using stackoverflow API. Here is my code:

app.get('/sof',function(req,res){
  var ark;
  request("https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=stackoverflow", function(error, response, body) {
    ark = body;
    console.log(body);
  res.send(ark);
  });
});

But, I get garbage values bot in browser and in logs.

How can I can resolver this issue? Everything else is running fine.

I am also using body-Parser:

var bodyParser = require('body-parser');
app.use(bodyParser.json());

EDIT: here is code that worked as explained by @Wainage in comments.

app.get('/sof', function(req, res){
    request.get({ url: "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=stackoverflow",
                  gzip: true },
        function(error, response, body) {
        console.log(body);       // I'm still a string
        body = JSON.parse(body); // Now I'm a JSON object

        res.json(body); // converts and sends JSON
    });
});

Solution

  • You got tripped up by the callback. The res.send will fire before the result is in.

    app.get('/sof',function(req,res){
      var ark;
      request("https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=stackoverflow", function(error, response, body) {
        ark = body;
        console.log(body);
        // res only when you get results
    
        //res.send(ark);
        res.json(body); // converts and sends JSON
      });
    });
    

    should work.

    EDIT: (include gzip deflation for this specific question)

    Per the StackExchange docs their results are served back gzip'd (makes sense). You need to tell request that is the case.

    app.get('/sof', function(req, res){
        request.get({ url: "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q=python%20best%20practices&site=stackoverflow",
                      gzip: true },
            function(error, response, body) {
            console.log(body);       // I'm still a string
            body = JSON.parse(body); // Now I'm a JSON object
    
            res.json(body); // converts and sends JSON
        });
    }