nodejs express application won't return json array

Go To StackoverFlow.com

1

I have the following express node.js app. It's using the 'redis' npm package.

app.get("/test",function(req,res){
    var data = [];
    client.HGETALL("receipts",function(err,obj){
        for(var id in obj){
            data.push(JSON.parse(obj[id]));
        }
    });
    console.log(data);
    res.json(data);
});

app.listen(3000);

The code run's without errors; however, the data variable is [] when it's returned to the browser. browser

The strange part is that when I run the same redis commands from the command line, the array is populated.

enter image description here

Can anyone tell me what's going on here?

2012-04-04 22:44
by Matt Phillips


9

Your code is asynchronous. The callback you pass doesn't get executed until after your console.log. Try:

app.get("/test",function(req,res){
    var data = [];
    client.HGETALL("receipts",function(err,obj){
        for(var id in obj){
            data.push(JSON.parse(obj[id]));
        }
        console.log(data);
        res.json(data);
    });
});
2012-04-04 22:46
by davin
Doh! I figured it was something like that. Originally i was just doing res.send(data) and i tried putting it inside the callback. But since that was wrong too i didn't see that was the solution. thank you - Matt Phillips 2012-04-04 22:51
@MattPhillips, that first method should've worked just fine! - davin 2012-04-04 22:56
so you can do res.send and pass json and it will set the headers properly? I swear it wasn't working - Matt Phillips 2012-04-04 23:00
@MattPhillips, depends what you mean by "properly". You can set the headers either way, although presumably (need to check) .send() uses text/html and .json() uses json headers. How important that is depends on your use case I suppose - davin 2012-04-04 23:03
well when the url i'm "GET"-ing in the client code expects application/json. So I'd say pretty important. That way I don't have to parse it back out on the client side - Matt Phillips 2012-04-04 23:05
Fair enough, then .json() seems like the more natural fit. Either way you can only execute them at the end of the callback. Take care - davin 2012-04-04 23:07
WORKS LIKE A CHARM !!! - Yasser Sinjab 2014-03-01 11:18
Ads