I am trying to get an array of image URLs inside Dropbox in JSON format. In order to do that, I have written the following function:
router.get('/thumbnails', function(req, res, next){
var images = [];
var imagesCount = -1;
var isLoggedIn = !!req.user;
var dropboxClient = req.app.get('dropboxClient');
console.log(dropboxClient);
dropboxClient.authenticate({interactive: false}, function(error, client) {
    if (error) {
        console.log(error);
        return 0
    }
    if (dropboxClient.isAuthenticated()) {
        dropboxClient.readdir(dropboxConfig.folder, function(error, entries) {
            if (error) {
                console.log(error);
                return 0
            }
            imagesCount = entries.length;
            entries.forEach(function(entry){
                var path = dropboxConfig.folder + '/' + entry;
                dropboxClient.makeUrl(path, {download: true}, function(err, res){
                    if(err){
                        console.log(err);
                        return 0
                    }
                    //console.log(res.url);
                    images.push({url: res.url});
                    console.log("Processed " + images.length + "/" + imagesCount);
                    if(images.length == imagesCount){
                        console.log(images);
                        res.json(images);
                    }
                });
            });
        });
    }
});
});
Upon observing the console output I believe all URLs are loaded into array, but the data is not available on the address http://.../thumbnails and after a while, if trying to load the data in the browser, it returns ERR_EMPTY_RESPONSE.
Does anyone know why the function doesn't return the data?
 
    